Stack Exchange Network

Stack Exchange network consists of 175 Q&A communities including Stack Overflow, the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Visit Stack Exchange

Questions tagged [variable]

A variable is a name, if correctly chosen with a symbolic meaning, that holds a value or values. Use this tag if your question is specific on the use of variables on shell scripting (if you want to ask about variables in programming languages you should probably ask on StackOverflow)

376
votes
3answers
263k views

Using “${a:-b}” for variable assignment in scripts

I have been looking at a few scripts other people wrote (specifically Red Hat), and a lot of their variables are assigned using the following notation VARIABLE1="${VARIABLE1:-some_val}" or some expand ...
98
votes
3answers
55k views

Are there naming conventions for variables in shell scripts?

Most languages have naming conventions for variables, the most common style I see in shell scripts is MY_VARIABLE=foo. Is this the convention or is it only for global variables? What about variables ...
78
votes
6answers
231k views

how can I add (subtract, etc.) two numbers with bash?

I can read the numbers and operation in with: echo "First number please" read num1 echo "Second number please" read num2 echo "Operation?" read op but then all my attempts to add the numbers fail: ...
61
votes
11answers
143k views

How do I check if a variable exists in an 'if' statement?

I need to check a variable's existence in an if statement. Something to the effect of: if [ -v $somevar ] then echo "Variable somevar exists!" else echo "Variable somevar does not exist!" ...
55
votes
5answers
82k views

Pass shell variable as a /pattern/ to awk

Having the following in one of my shell functions: function _process () { awk -v l="$line" ' BEGIN {p=0} /'"$1"'/ {p=1} END{ if(p) print l >> "outfile.txt" } ' } , so when called as ...
43
votes
9answers
171k views

How to assign a string value to a variable over multiple lines while indented?

The issue: I need to assign a variable a value that is decently long. All the lines of my script must be under a certain number of columns. So, I am trying to assign it using more than one line. It'...
36
votes
3answers
4k views

Why is opening a file faster than reading variable content?

In a bash script I need various values from /proc/ files. Until now I have dozens of lines grepping the files directly like that: grep -oP '^MemFree: *\K[0-9]+' /proc/meminfo In an effort to make ...
33
votes
2answers
44k views

In Bash scripting, what's the meaning of “ $! ”?

If I'm assigning a variable with temp=$! what would it be its value?
33
votes
2answers
33k views

In bash scripting, what's the different between declare and a normal variable?

In bash scripting: we create variable by just naming it: abc=ok or we can use declare declare abc=ok what's the difference? and why does bash make so many ways to create a variable?
32
votes
4answers
283k views

how to concatenate string variables into a third?

I need to concatenate two strings in bash, so that: string1=hello string2=world mystring=string1+string2 echo mystring should produce helloworld
32
votes
3answers
125k views

Test if a string contains a substring

I have the code file="JetConst_reco_allconst_4j2t.png" if [[ $file == *_gen_* ]]; then echo "True" else echo "False" fi I test if file contains "gen". The output is "False". Nice! The ...
31
votes
4answers
68k views

Assigning exit code to a shell local variable

#!/bin/bash function0() { local t1=$(exit 1) echo $t1 } function0 echo prints empty value. I expected: 1 Why doesn't t1 variable get assigned the exit command's return value - 1?
24
votes
4answers
29k views

Scope of Local Variables in Shell Functions

After reading 24.2. Local Variables, I thought that declaring a variable var with the keyword local meant that var's value was only accessible within the block of code delimited by the curly braces of ...
23
votes
5answers
2k views

Why use double quotes in a [[ ]] test?

Let's say we have 2 integers in a bash script: value1=5 value2=3 Then why do we need to use double quotes in case of a test ? For example: if [[ "$value1" -eq "$value2" ]] Why not just use the ...
23
votes
1answer
11k views

Why does awk print the whole line when I want it to print a variable?

When I type: echo "foo bar" | gawk -v var="content" '{print $var}' I expect the output to be content. Why is it foo bar?
22
votes
4answers
20k views

Why is my variable local in one 'while read' loop, but not in another seemingly similar loop?

Why do I get different values for $x from the snippets below? #!/bin/bash x=1 echo fred > junk ; while read var ; do x=55 ; done < junk echo x=$x # x=55 .. I'd expect this result x=1 cat ...
20
votes
3answers
7k views

How can we run a command stored in a variable?

$ ls -l /tmp/test/my\ dir/ total 0 I was wondering why the following ways to run the above command fail or succeed? Thanks. $ abc='ls -l "/tmp/test/my dir"' $ $abc ls: cannot access '"/tmp/test/my':...
20
votes
2answers
50k views

How to insert variables inside a string containing “”?

I want to construct an xml string by inserinting variables: str1="Hello" str2="world" xml='<?xml version="1.0" encoding="iso-8859-1"?><tag1>$str1</tag1><tag2>$str2</tag2&...
19
votes
5answers
2k views

Variable randomly chosen among three numbers (10, 100, and 1000)

Is it possible to have variable which picks a random number from three pre-decided numbers? Sample: var= 10 or 100 or 1000
19
votes
2answers
7k views

Setting a shell variable in a null coalescing fashion

I'm really fond of "null coalescing", where you can set a variable to the first "non-null" value in a list of things. Many languages support this, for example: C#: String myStr = string1 ?? string2 ?...
19
votes
3answers
2k views

How can I expand a quoted variable to nothing if it's empty?

Say I have a script doing: some-command "$var1" "$var2" ... And, in the event that var1 is empty, I'd rather that it be replaced with nothing instead of the empty string, so that the command ...
19
votes
2answers
83k views

How to assign the cat output of a bash script to a variable in another script

I have a bash script that produces a cat output when it takes an argument. I also have another bash script that executes the first bash script with an an argument that I want to produce cat outputs ...
18
votes
6answers
662 views

Should variables be quoted when executed?

The general rule in shell scripting is that variables should always be quoted unless there is a compelling reason not to. For more details than you probably want to know, have a look at this great Q&...
18
votes
1answer
1k views

Why does ${$#} return same result as $$ in the shell?

While trying to get last positional parameter set in /bin/dash , I've tried echo ${$#}. Surprisingly this did not result in an error, but into PID which is the same as $$ variable contents. Question, ...
17
votes
3answers
2k views

Why do options in a quoted variable fail, but work when unquoted?

I read about that I should quote variables in bash, e.g. "$foo" instead of $foo. However, while writing a script, I found an a case where it works without quotes but not with them: wget_options='--...
17
votes
4answers
71k views

shortest way to replace characters in a variable

There are many ways to replace characters in a variable. The shortest way I found out is tr so far: OUTPUT=a\'b\"c\`d_123and_a_lot_more OUTPUT=$(echo "$OUTPUT"|tr -d "'\`\"") echo $OUTPUT Is there ...
17
votes
4answers
15k views

dirname and basename vs parameter expansion

Is there any objective reason to prefer one form to the other? Performance, reliability, portability? filename=/some/long/path/to/a_file parentdir_v1="${filename%/*}" parentdir_v2="$(dirname "$...
17
votes
5answers
49k views

Pipe assigns variable

For simplicity I would like to do: echo cart | assign spo; echo $spo Output: cart Does such an assign application exist? I am aware of all the ways to do this using substitution.
15
votes
3answers
79k views

How can I concatenate a shell variable to other other parameters in my command lines ?

How can I concatenate a shell variable to other other parameters in my command lines? For example, #!/bin/sh WEBSITE="danydiop" /usr/bin/mysqldump --opt -u root --ppassword $WEBSITE > $WEBSITE....
13
votes
4answers
2k views

Is it possible to print the content of the content of a variable with shell script? (indirect referencing)

Let's suppose I've declared the following variables: $ var='$test' $ test="my string" If I print their contents I see the following: $ echo $var $test $ echo $test my string I'd like to find a ...
13
votes
2answers
1k views

How can variables use “~” for cd'ing?

How can I use a variable - $BASE in my cd. I tried the following but I get an error $ cd ~/z/repo_1_ruby_193/ 23:23:57 durrantm Castle2012 /home/durrantm/z/repo_1_ruby_193 $ BASE="~/z" 23:24:03 ...
13
votes
8answers
1k views

Reversing a variable's contents by words

So if I've got a variable VAR='10 20 30 40 50 60 70 80 90 100' and echo it out echo "$VAR" 10 20 30 40 50 60 70 80 90 100 However, further down the script I need to reverse the order of this ...
12
votes
2answers
24k views

Remove specific word in variable

In a bash script, how can I remove a word from a string, the word would be stored in a variable. FOO="CATS DOGS FISH MICE" WORDTOREMOVE="MICE"
12
votes
3answers
4k views

Spaces in variable assignments in shell scripts

What is the difference between below variables assignments? var=23 var =23 var= 23 var = 23 Is there any difference in space around the assignment operator?
12
votes
2answers
7k views

How to store an image file in bash variable?

After I use the following command, pngString="$(cat example.png)" echo -n "$pngString" > tmp.png I can't open the tmp.png as a PNG file. Maybe some information is lost when I use $pngString ...
12
votes
1answer
575 views

See the expansion of Bash variables for debugging?

Is there any tools/tricks available for expanding variables to make bash code easier to read? For example it would convert the following: DIR=/var/tmp FILE=${DIR}/file SCRIPT_ROOT=/opt/root TOOL=${...
11
votes
2answers
885 views

How to make `local` capture the exit code?

In my project I have the following snippet: local output="$(bash "${1##*/}")" echo "$?" This always prints zero due to local, however, removing local causes the $? variable to behave correctly: ...
11
votes
4answers
3k views

Why is the JSON content from heredoc not parsable?

I have a JSON fragment. The following does not work: VALUE=<<PERSON { "type": "account", "customer_id": "1234", "customer_email": "jim@gmail.com" } PERSON echo -n "$VALUE" | python -m ...
11
votes
3answers
2k views

How do I echo an empty JSON curly brackets as a default value?

I can't seem to get an empty JSON {} to echo if an envvar is missing. I either have a trailing } in the output if set, or the escape displays. bash-3.2$ unset X bash-3.2$ echo "${X:-{}}" {} bash-3.2$ ...
11
votes
2answers
3k views

How do I shift a bash array at some index in the middle?

1 #!/bin/bash 2 # query2.sh 3 4 numbers=(53 8 12 9 784 69 8 7 1) 5 i=4 6 7 echo ${numbers[@]} # <--- this echoes "53 8 12 9 784 69 8 7 1" to stdout. 8 echo ${numbers[i]} # <--- this echoes ...
11
votes
4answers
26k views

Escape a variable for use as content of another script

This question is not about how to write a properly escaped string literal. I couldn't find any related question that isn't about how to escape variables for direct consumption within a script or by ...
11
votes
5answers
8k views

Number of characters in a shell command's output

I am writing a script which needs to calculate the number of characters in a command's output in a single step. For example, using the command readlink -f /etc/fstab should return 10 because the ...
11
votes
2answers
41k views

How to use variables inside single quotes

I have an application which takes as an input attributes in double quotes embedded in single quotes. Take for example this right command: command -p 'cluster="cl1"' In order to automate it, I ...
10
votes
2answers
41k views

How to increment local variable in Bash?

Data 1 \begin{document} 3 Code #!/bin/bash function getStart { local START="$(awk '/begin\{document\}/{ print NR; exit }' data.tex)" echo $START } START2=$(getStart) echo $START2 ...
10
votes
2answers
12k views

How to store pipe ( | ) in a variable?

The idea would be to use it as... a pipe in a command. For instance: say there's some kind of long path which has to be retyped again and again, followed by a pipe and a second program, i.e. "...
10
votes
2answers
2k views

Can you explain these three things in this bash code for me?

I have a function in my .bashrc file. I know what it does, it steps up X many directories with cd Here it is: up() { local d="" limit=$1 for ((i=1 ; i <= limit ; i++)) do ...
10
votes
2answers
6k views

Using shell variables for command options

In a Bash script, I'm trying to store the options I'm using for rsync in a separate variable. This works fine for simple options (like --recursive), but I'm running into problems with --exclude='.*': ...
10
votes
3answers
17k views

Define variables with a variable name

What's wrong with this script? I'm trying to define A1=1, B1=1, C1=1 LIST="A B C" for x in $LIST do "$x"1=1 done and the result is: ./x.: line 7: A1=1: command not found ./x.: line 7: B1=1: ...
10
votes
2answers
1k views

Initializing Bash variables - Is it required, recommended or define as you go

Is there any advantage/disadvantage of initializing the value of a bash variable in the script, either before the main code, or local variables in a function before assigning the actual value to it? ...
10
votes
2answers
762 views

Why can I not use variables as prefix to a command to set environment variables?

Normally, it is possible to set an environment variable for a command by prefixing it like so: hello=hi bash -c 'echo $hello' I also know that we can use a variable to substitute any part of a ...