Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy a variable in shell script (Linux)

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"
like image 760
ojhawkins Avatar asked Apr 06 '26 20:04

ojhawkins


2 Answers

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
like image 195
fedorqui 'SO stop harming' Avatar answered Apr 09 '26 12:04

fedorqui 'SO stop harming'


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

like image 24
hek2mgl Avatar answered Apr 09 '26 12:04

hek2mgl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!