3

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"
3
  • 1
    why cp? what's wrong with x="$1" then echo "copied value:$x" Commented Jul 16, 2013 at 12:05
  • 1
    He has a Barbeque, but He wants his chicken roasted only with a Rocket Propeller! Commented Jul 16, 2013 at 12:08
  • 1
    +1 for most excellent use of cp this year. Commented Jul 16, 2013 at 12:43

5 Answers 5

3

Note that cp is used to copy files and directories. To define variables, you just have to use the following syntax:

v=$1

Example

$ 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
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0
val=$1  
echo "Copied Value : $val"

Comments

0

You are using cp which is for copying files.

Just use

v=$1

and echo it:

echo "Copied Variable: $v"

1 Comment

why repeating things that had been said before?
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.