How can I copy a variable to another variable in a shell script?
Assuming the user has passed in $1, how can its value be copied to another variable?
I assume it would look something like this...
cp $1 $2
echo "Copied value: $2"
Firstly cp is for copying files and directories only (as the man page states)
Secondly, it is not possible to assign to an argument variable ($0..$1..$n). They are meant to be read only.
You can do this instead:
input2=$1
It will copy the value of $1 to a new variable called $input2
You are using cp which is for copying files.
Just use
v=$1
and echo it:
echo "Copied Variable: $v"
i've found set -- to be a very useful command to set the positional parameters. e.g. in the example you gave, and well answered:
cp file1 file2
copies "file1" to "file2". frequently when i work with a few files, I'll do this instead:
set -- file1 file2
cp $1 $2
and if you want to reverse the names in the variables:
set -- $2 $1 # puts the current "$2" value in "$1", and vice versa, then
cp $1 $2 # copies what was file2 contents back to file1.
this without using any "named" variables, which you've already seen. my more common use is like:
set -- ${1%.txt} # strips a ".txt" suffix
set -- $1 $1.out $1.err # sets 2nd to <whatever>.out and 3rd to <whatever>.err, so
cmd $1.txt > $2 2>$3 # puts stdout in ...out and stderr in ...err
v
cp? what's wrong withx="$1"then echo "copied value:$x"cpthis year.