Linux Script Variables
What Are Shell Script Variables?
A variable in a shell script is a means of referencing a numeric or character value. And unlike formal programming languages, a shell script doesn't require you to declare a type for your variables. Thus, you could assign a number to the variablestuff=5
stuff='chocolate truffles'
Don't put any spaces before or after the equal sign, or you'll get an error. And if you want to assign a string that contains spaces, you will need to put quotation marks around the string.
This is a good time to note that there are several distinct ways to use quotations marks in a shell script. Let's look at the differences among single quotation marks, double quotation marks, and the backslash character and then follow up with some examples.
· Single quotation marks, as in the preceding example, will always get you exactly what's inside the quotation marks--any characters that might otherwise have special meaning to the shell (like the dollar sign or the backslash) are treated literally.
· Use double quotation marks when you want to assign a string that contains special characters the shell should act on.
· The backslash is used to escape (treat literally) a single character (such as $ or *) that might otherwise be treated as a special character by the shell.
Now let's look at some examples that show when to use each method of quoting.
howdy='Good Morning $USER !'
echo $howdy
Good Morning $USER !
howdy="Good Morning $USER !"
echo $howdy
Good Morning hermie !
In the first case, the value of the howdy variable would probably not be what you wanted. The single quotation marks caused Bash to not treat $USER as a variable. In the second case, the results look much better. The double quotation marks allowed Bash to substitute the value of $USER, which is set automatically when you log in, in the string.
Here's another example that demonstrates a common error:
costmsg="Price is $5.00"
echo $costmsg
Actual result: Price is .00
We thought enough to quote the string, but the dollar sign tells Bash to use the value in the $5 variable, which is not what we wanted.. We can easily solve the problem by prefixing the dollar sign with a backslash, as shown here:
$ costmsg="Price is \$5.00"
$ echo $costmsg
Actual result: Price is $5.00
Arguments and Other Special Variables
Arguments are the values you pass to a shell script. Each value on the command line after the name of the script will be assigned to the special variables $1, $2, $3, and so on. The name of the currently running script is stored in the $0 variable.
Here are some other special variables you will find useful in script writing:
$# The number of arguments
$* The entire argument string
$? The return code from the last command issued
So let's try some examples working with arguments and other special variables. Create an executable script called testvars containing these lines:
echo "My name is $0"
echo "First arg is: $1"
echo "Second arg is: $2"
echo "I got a total of $#
arguments."
echo "The full argument string was: $*"
Now if you run this script, here's what you'll see:
$ ./testvars birds have lips
My name is testvars
First arg is: birds
Second arg is: have
I got a total of 3 arguments.
The full argument string was: birds have lips
Previous Lesson: Executing a Script
Next Lesson: Shell Script Logic
Comments - most recent first
(Please feel free to answer questions posted by others!)
My script looks like below:
echo "Enter the no.s:"
Now I want to assign each no. to different variables.
For eg: If user inputs 35 56 85, then I need:
var1=35
var2=56
var3=85
Thanks in advance.
for example:
script1.sh
value1=90
value2=91
value3=93
script2.sh
echo $value1
echo $value2
echo $value3
if [ "$value1" -eq "$value2" ]; then
echo "$value1 is greater than $value2"
else
echo "$value1 is less than $value2"
#-----------------
#including common.func file - common functions #are now available to be called from this script
. ${script_home}/common.func
. ${PROPERTIES} $1
I am new to Unix and have been tasked with:
Provided the following expression is used for adding two numbers in BASH:
`expr $1 + $2`
Develop a script that takes as input two numbers ($1, and $2), and adds the two numbers. If no input is provided, then exit with an error message.
I am stumped.I have been looking for hours. This expr has got me. Any and all help greatly appreciated
its too good. keep it up......
thanks
actually we want a program in linux ,in which the program take any n real value and give their sum average mini. & max value
but our program is taking only int. value . it is not taking desimal & negative value
the tast is not accept desimsal(2.3 etc.) value
FTP_IP_ADD_2=11.11.11.11
FTP_IP_ADD_3=12.12.12.12
TOTAL=3
count=0
while [[ $count -lt $TOTAL ]]
do
echo $count
count=$((count + 1))
ADDRESS=FTP_IP_ADD_$count
echo "$ADDRESS" #This will print FTP_IP_ADD_1,FTP_IP_ADD_2,FTP_IP_ADD_3
#(I want IP Address to be printed)
done
echo 'date'
*10.3569* etc.
now i need get the data before the dot(.). for that i used cut command and tried to compare the cut value with dot(.). but it is showing error integer is expecting.
I am writing simple shell script i need to prefix the values of x and y with 'C'. Please advice.
#!/bin/bash
x=$(date +%Y%m%d)
echo $x
a=1
b=2
c=3
d=4
e=5
f=6
y= expr $x - $a
echo $y
I have a situation where I need to refer to a variable that is "encapsulated" in single quotes ('). When I run the follwing, it does not recognize the variable. The value for name has to be surrounded by single quotes, otherwise it will yield errors. I've thought about using another value for the table entry, but all others are either too common or will not be known at the time this script is run. The program I am using to run this does not yield any errors.
query=$"`./query - @10.0.0.50 -d -a TABLE -w \"name: == '$DBPath'\" -s DELETE`"
echo $query
I have another command that adds data to the table that follows this same format, but there are no instances in that code where the variable is encapsulated in single quotes. Below:
post=$"`./mposter -n @10.0.0.50 -d -a TABLE -b \"name=$DBPath;description=Automated_Blackout_of_$DBPath;start=$StartDate;e nd=$EndDate`"
set DATEE=`date -d "yesterday" +"%m%d%y"`
cat file1.TXT file2.TXT file3.TXT > ${DATEE}newfile.txt
It works okay if I put the date varible at the end of newfile$DATEE.txt
Any help is appreciated.
True or Flase?
lets say ive got the following string stored in mysql database in column 'info' of table 'TBL':
"ur name is $name"
and lets say ive got this code :
=================================================
#bin/bash
echo -n "enter your name: ";
read -e $name; /*read input from user an store it in $name*/
result=$(mysql -u USER -p -e "use xyz_db; select info from TBL where id=1;);
echo $result;
================================================
I want the string retrieved from database and stored in the variable "result", ("ur name is $name"), to be opened some how in this code so that the user supplied input of "$name" in this code be put in the variable "$name" of the retreived string from data base.
so when it asks: and a name is entered, like
enter your name: jhon
it should put that value in the string retrived from database which contains variable $name. and the out put should come as:
"ur name is jhon"
===============================================
its something that i need to do...and its getting very annoying. its my requirment that the string stored in the database should contain the variable that will store the input given by the user in the program.
I would REALLYY apriciate any bright ideas or ways or changes in this code to make this work.
best regard
Desperate_scripter
I am new in shell scripting. I have a lit of files like this:
BN090101
BN090102
.
.
BN090201
.
.
I want to read these file 1 by 1 and copy them to another directory. I mean copy for example first one then second one and so on. not all together. what should I do?
plz help
#!/bin/sh -x
equa_vma1="c0c1153a3024cf83-vma1"
equa_vma2="5a81153a3054cf83-vma2"
equa_vma3="c981153a3084cf83-vma3"
setup_80g ()
{
op=$1
initial=$2
max=$3
for i in $(seq $initial $max)
do
iqn="equa_vma$i"
echo $iqn
done
}
setup_80g a 1 2
I am writing a script that reads a list of paths/directories and then enters each directory and create a folder with a name extracted from the name of this directory,
for example:
I have path to be ../gcm/peter
i have to get into ../gcm/peter and create a folder named shared_peter
here is my script (I need to change "shared" into shared_peter, which is part of $DIR):
#! /bin/sh
while read DIR
do
cd $DIR
echo "------------------------------------------------"
echo "I am in directory"
echo $DIR
echo "Creating shared directory"
mkdir -p shared
ls $DIR/
cd
echo "------------------------------------------------"
done
exit 0
thanks for the help
file content.....abc.cfg
# Temporary use by Boyajian. Thank you.
# Plz feel free to change as per ur need. Thnx - Ayan
###---SBJ_VIEW_NAME=devB_4140sdd
#SBJ_VIEW_NAME=bagay_dev_mts_1440sdd
SBJ_VIEW_NAME=devD_4018
#SBJ_VIEW_NAME=devD_4017
ACE_MATCH_SERVER_HOST=localhost
ACE_MATCH_SERVER_PORT=16711
ACE_JASI_SERVER_PORT=75675
ENT_CLIENT_HOSTS=localhost,imts1,charon
ENT_SERVER_PORT=45785
ENT_SERVER_HOST=imts1
ENT_VIRTUAL_MEMORY=1000000000
ENT_NUM_ACCUMULATORS=8
SBJ_NO_SIG_CHECK=1
AREA_PROD_BRANCH=s2010
now if i want to update the value of ACE_MATCH_SERVER_PORT from 16711 to 78777
what would be the code to do this stub? please give a solution at the earliest
m=3
n=2
c=`expr $m / $n`
echo "$c"
this prints integer value
i need float value to be printed
pls help soon
echo out the result
I am having no luck with this PLS HELP !!!
but,please disccusing the variable like
integer,float,double,and so on
"how work with it's"
thank you.
This my config:
*********************************************
#!/bin/sh
# assign a value:
while :
do
clear
echo "-------------------------------------"
echo " Menu Principal "
echo "-------------------------------------"
echo "[1] Para verificar si esta configurado el mac"
echo "[2] Para verificar y agregar mac address"
echo "[3] Salir/Cancelar"
echo "======================="
echo -n "Entre su seleccion de [1-3]: "
read yourch
case $yourch in
1) echo "Introducir los 4 ultimos digitos del mac-address:" $fname
read $fname
echo "grep $fname /etc/vmps.dd" ;;
************************************************
But do nothing.
I found the issue; the list "$*" should be "$@"
Works great.
for item in "$*"
do
echo "Argument value is: $item"
done
To run the file, I use:
./test a b c
The result I got was:
Argument value is: a b c
Why did the script put 'a b c' into one value?
Should I have seen:
Argument value is: a
Argument value is: b
Argument value is: c
When running the program, the question format seems to be screwed up (all questions on one line? and the answers are blank?) but the programs results are correct so the fortran must have recognized the answers from the text file. Thanks again.
xx1 < input.txt
As an example, I run the program (called xx1):
>xx1
Do you want ascii output (y,n)?
>y
Do you want to use data1 (1) or data2 (2)?
>2
Do you want a pos plot (1) or a vel plot (2)?
>1
>
I want to record the answers for specific runs so I want to create a script where the answers are recorded and the script runs the program.
If I type on command line:
>xx1 y 2 1
this doesn't work.
How can I write a script to run xx1 with the answers to the questions in it, so I don't have to answer the questions each time?
In other words,
find . exec | grep "text to search for" '{}' \;
Called it myfind
find . exec | grep $1 '{}' \;
>myfind "text to search"
does not work
This does not work.
ARRAY=("ONE A Z" "TWO B Y" "THREE C X")
# for I in ${ARRAY[*]} # Each Item in the Array is listed.
# for I in ${ARRAY[@]} # Each Item in the Array is listed.
# for I in "${ARRAY[*]}" # Each String in the Array is Concatenated.
for I in "${ARRAY[@]}" # Each String in the Array is listed.
do
echo "LOOP START:"
echo $I
echo ${I[*]}
echo ${I[@]}
echo ${I[0]}
LOOP_ARRAY=($I)
echo LOOP ARRAY:
echo $LOOP_ARRAY # 1st Item of Loop Array
echo ${LOOP_ARRAY[0]} # 1st Item of Loop Array
echo ${LOOP_ARRAY[1]} # 2nd Item of Loop Array
echo ${LOOP_ARRAY[2]} # 3rd Item of Loop Array
done
cheers!!
I welcome your comments. However... I am puzzled by many people who say "Please send me the Linux tutorial." This website *is* your Linux Tutorial! Read everything here, learn all you can, ask questions if you like. But
don't ask me to send what you already have. :-) NO SPAM! If you post garbage, it will be deleted, and you will be banned.
Copyright © by -
All rights reserved - Redistribution is allowed only with permission.


