Shell Script Variables:
Variable in shell script means, referencing a numeric or character value. We can access the value of a variable, prefix it with a dollar sign. eg:
value=5 or value ='linuxfunda' echo $value
Here the variable name is “value “. We can access it’s value by writing $value.
Example 1:
Storing character value in a variable
#!/bin/bash name='linuxfunda' echo "Hi My name is $name."
Example 2:
Storing numeric value in a variable
#!/bin/bash value1=5 value2=3 value3=$(($value1 + $value2)) echo "The total of Value1 and Value2 is: $value3"
Arguments and Other Variables:
Arguments are the values we are passing to a shell script. Each value after the script in the command line will be assigned to a special variables like $1, $2, $3 and so on. The name of the script will be store in the variable $0.
$# -The number of arguments $* -The entire argument string $? -The return value from the last command issued
The above are some special variables in shell script.
Example 3:
#!/bin/bash echo "The Script Name is: $0" echo "First Argument is: $1" echo "Second Argument is: $2" echo "Number of Arguments are: $#" echo "You have entered these Arguments: $*"
Usage:
./script.sh One Two Three
Output:
The Script Name is: script.sh First Argument is: One Second Argument is: Two Number of Arguments are: 3 You have entered these Arguments: One Two Three
Read-Only Variables:
The shell provides a way to mark the variables are read-only. If a variable will set are read-only then it’s value can’t be change.
#!/bin/sh NAME="linuxfunda" readonly NAME NAME="tapas"
This will produce result as below:
/bin/sh: NAME: This variable is read only.
Unsetting Variables:
Unsetting or deleting a variable tells the shell to remove the variable from the list of variables that it tracks. Once you unset a variable, you would not be able to access stored value in the variable.
#!/bin/sh NAME="Zara Ali" unset NAME echo $NAME
The above script would not print anything.