Reputation: 3288
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"
Upvotes: 3
Views: 12971
Reputation: 366
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
Upvotes: 0
Reputation: 169
You are using cp
which is for copying files.
Just use
v=$1
and echo it:
echo "Copied Variable: $v"
Upvotes: 0
Reputation: 158070
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
Upvotes: 1
Reputation: 289955
Note that cp
is used to copy files and directories
. To define variables, you just have to use the following syntax:
v=$1
$ cat a
echo "var v=$v"
v=$1
echo "var v=$v"
$ ./a 23 <---- we execute the script
var v= <---- the value is not set
var v=23 <---- the value is already set
Upvotes: 3