-2

I have a text file into which i want to pass my command line argument. eg:

./scriptname.sh abc.sh 

What is the command that I can write inside scriptname.sh to copy abc.sh to a text file, say new.txt ?

0

Bourne-like shells

In Bourne-like shells (as your .sh extension suggests you're using for your scripts):

#! /bin/sh -
if [ "$#" -gt 0 ]; then # if I was given at least 1 argument
  cp -- "$1" new.txt # where $1 is the first argument... $9 the 9th
                     # and ${10} the 10th (not $10 which is ${1}0)
else
  echo >&2 Not given enough arguments
  exit 1
fi

(note the need for -- to mark the end of options to make sure the $1 is not taken as an option to cp if it starts with -).

A shorter way to check that at least one argument was given is with:

#! /bin/sh -
cp -- "${1?Not given enough arguments}" new.txt

Where ${parameter?message} causes the shell to exit with an error including the message if the parameter is not set.

Or if you're really lazy:

#! /bin/sh -u
cp -- "$1" new.txt

Where -u causes the shell to exit upon any parameter expansion where the parameter is unset.

To copy all the arguments:

#! /bin/sh -
if [ "$#" -gt 0 ]; then # if I was given at least 1 argument
  cp -- "$@" /some/dir/ # where "$@" expands to all the script's
                        # arguments as separate arguments to cp
else
  echo >&2 Not given enough arguments
  exit 1
fi

(portably, you can't rely on ${@?...} or -u to exit the script if there's no argument).

To loop over the arguments, that's what the for construct loops on by default:

#! /bin/sh -
for file do
  cp -- "$file" "$file.new"
done

Though of course you can also do:

#! /bin/sh -
for file in "$@" do
  cp -- "$file" "$file.new"
done

to make it explicit (but less efficient in some shells).

Other shells

(leaving the arg count check aside)

  • csh/tcsh

    cp -- $1:q new.txt # one argument, properly quoted
    cp -- $argv:q /some/dir # all arguments
    
  • rc/es:

    cp -- $1 new.txt
    cp -- $* /some/dir
    
  • fish

    cp -- $argv[1] new.txt
    cp -- $argv /some/dir
    
  • You may also need to validate if it's a file also. – αғsнιη Nov 2 '17 at 8:27
  • 1
    @αғsнιη, cp will do that for you. What may be needed though is to check that new.txt is not a directory as cp would then copy $1 into it instead of failing to copy to it (unless you use the GNU-specific -T option). – Stéphane Chazelas Nov 2 '17 at 8:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.