Linux – Copy a variable in a shell script (Linux)

Copy a variable in a shell script (Linux)… here is a solution to the problem.

Copy a variable in a shell script (Linux)

How do I copy one variable to another in a shell script?

Assuming the user passes in $1, how do you copy their value to another variable?

I’m assuming it looks like this….

cp $1 $2

echo "Copied value: $2"

Solution

Note that cp is used to copy files and directories. To define a variable, you simply 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

Related Problems and Solutions