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)

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 ...
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 ...
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':...
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?
375
votes
3answers
262k 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 ...
8
votes
2answers
2k views

Use a shell variable in awk

Here is my script (to find the files that contain a specified pattern): find . -type f \ -exec awk -v vawk="$1" '/'"$vawk"'/ {c++} c>0 { print ARGV[1]; exit 0 } END { if (! c) {exit 1}}' \{\} \...
4
votes
2answers
334 views

Command substitution declaration syntax in bash - which of these two is better practice? [duplicate]

This is part of a bash find loop, and I wondered which is more correct syntax and why? filename="$(echo "$i" | cut -c5-)"; filename=`echo "$i" | cut -c5-`; Both function for the purpose of getting ...
61
votes
11answers
142k 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!" ...
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 "$...
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: ...
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 ...
7
votes
4answers
21k views

bash dynamic (variable) variable names

I want to dynamically create a sequence of strings by manipulate an array of elements and create some arithmetic procedure. for name in FIRST SECOND THIRD FOURTH FIFTH; do $name = $(( $6 + 1 )) ...
8
votes
2answers
2k views

Indirectly expand variables in shell

I need to indirectly reference a variable in the bash shell. I basically want to what you can do in make by writing $($(var)). I have tried using ${$var} which would be the most straight forward ...
5
votes
6answers
13k views

creating variable using variable value as part of new variable name

I'm trying to create a new variable using the value of an existing variable as part of the variable name. filemsg"$word1"=" " I've also tried filemsg$word1=" " filemsg${word1}=" " on all ...
3
votes
3answers
6k views

Why is the array empty after the while loop? [duplicate]

I try to initialize an array in bash-4.2 next way: ring=() ls -las | tail -n +4 | while read line > do > ring+=("$line") > echo ${ring[-1]} > done 3924 -rw-r--r-- 1 username group 4015716 ...
7
votes
1answer
403 views

Circular name references in bash shell function, but not in ksh

I'm writing a set of shell functions that I want to have working in both Bash and KornShell93, but with Bash I'm running into a "circular name reference" warning. This is the essence of the problem: ...
8
votes
2answers
1k views

How is the return status of a variable assignment determined?

I have seen constructs in scripts such as this: if somevar="$(somecommand 2>/dev/null)"; then ... fi Is this documented somewhere? How is the return status of a variable determined and how does ...
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?
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 ...
3
votes
4answers
2k views

bash array with variable in the name

I'll appreciate your help with the following issue: I'm trying to set an array which contains a variable as part of the array name, example: Arr_$COUNTER (where $COUNTER is changed based on a loop ...
9
votes
3answers
1k views

Why doesn't bash expand this variable when I prefix a command with a “one time variable assignment” [duplicate]

If I run this bash command and prefix the statement, so that the variable fruit should exist, but only for the duration of this command: $ fruit=apple echo $fruit $ The result is an empty line. why?...
5
votes
2answers
3k views

When should one use $( ) in defining variables

Some shell scripts I have come across use the following syntax when defining variables: file_list_1=$(echo "list.txt") or file_list_2=$(find ./) I would have used: file_list_1="list.txt" and ...
4
votes
1answer
1k views

mv : not found when executed from script that modifies PATH variable

I have this in my script. But is returning an error. If I execute the command in the console works fine ./script.sh[16]: mv: not found [No such file or directory] I want move some files what starts ...
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
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='.*': ...
5
votes
4answers
4k views

How do I output a suggestion for a user to accept and use as input?

What can I do to leave the cursor on the same line of the suggestion in a Bash script? Bash version = 3.2.51 It's purpose is to suggest a string so that the user should only press Enter. #!/bin/sh ...
3
votes
2answers
864 views

Assign specific line from a variable to another variable

I would like to take a specific line from a variable to another variable. I tried this but it doesn't work: c="1.apple 2.banna 3.peach" read "Please choose fruit [1-3]:" t a=$c | awk "NR==$t" echo "...
3
votes
2answers
2k views

How can I get `expect` to ignore $ (dollar sign) in a password?

I'm running an expect script and the password has a $ character. The shell looks for the following characters to expand into something and spits out no such variable. Is there any way around this?
1
vote
3answers
16k views

How do I get a variable's value from one script and import it in another script?

How do I get a variable's value from one script and import it in another script? But the catch is that the script where I am going to get the variable's value has also some commands that I don't want ...
4
votes
5answers
29k views

How to use a shell variable inside sed's s command? [duplicate]

we know that we can get the value of a variable using $ sign: x=3 echo $x 3 Is there other ways that we can use to get the value without using $ sign. I'm asking this because $ sign is a special ...
4
votes
3answers
3k views

How can I set an environment variable which contains newline characters?

I'm trying to set an RSA key as an environment variable which, as a text file, contains newline characters. Whenever I attempt to read from the file and pass it into an environment variable, it will ...
3
votes
4answers
3k views

Can I determine type of an awk variable?

I have the gawk version of awk. In this part of gawk manual, it is stated that awk variables have "attributes", which are used to determine how to treat them in various operations. For example, a ...
3
votes
1answer
198 views

How to know where shell variables and functions are set?

When I type the set command in my system I've got this extract out : __colormgr_commandlist=' create-device create-profile delete-device delete-profile device-add-profile ...
3
votes
1answer
197 views

Bash string range and replace

To print part of the string, replace , with . I use command: echo "${q:16:6}" | sed 's/,/./' Is it possible to use something like: echo "${q:16:6/,/.}" because it does not work?
2
votes
1answer
3k views

Append same timestamp to multiple filenames

I have several files that I ftp each hour. The receiving system needs to have some sort of identifier that they came from the same batch, so I would like to append a timestamp to the filename. That ...
2
votes
1answer
9k views

Get the output from expect script in a variable

I have an expect script which provides the IP address: #!/bin/expect -f set nodename [lindex $argv 0] spawn virsh console $nodename expect "Escape character is" send "\n" expect "localhost login: " { ...
1
vote
2answers
155 views

Why did $id disappear after the EOF

cat >run_pos2bed3.sh <<EOF ls 2*/peaks.txt | while read id; do echo $id done; EOF after input it nano only show ls 2*/peaks.txt | while read id; do echo done; EOF How can I add $id after ...
1
vote
3answers
3k views

How to pass directory with escaped space to variable?

I have a small test.sh script as follows: #!/bin/bash read -e -p "Enter a Directory: " directory echo $directory Here's what happens when I run it: $ ./test.sh Enter a Directory: ~/A\ Directory/ /...
-1
votes
2answers
49 views

The need for $1 and $2 for comparison with an here-string

This is a follow up to this question; I don't know why but I keep misunderstanding the following code, although I try very hard to understand it: function read_and_verify { read -p "$1:" tmp1 ...
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'...
7
votes
1answer
570 views

Word splitting in positional parameters

Consider the following example: IFS=: x="a :b" # three spaces echo ["$x"] # no word splitting # [a :b] # as is echo [$x] # word splitting # [a b] # four spaces Word splitting ...
2
votes
2answers
2k views

What is the best way to find the current DISPLAY and XAUTHORITY in non interactive shell for the current user? [duplicate]

I have a project that needs to detect the DISPLAY in shell (bash) variable to be able to display some gui stuff on the local machine. Or a better solution (dbus ?) to open gui stuff in non ...
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....
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: ...
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 ...
6
votes
1answer
19k views

Appending to same array in various loops, only last values remain Bash 4

I have something like this: FILES=() for i in *.map do FILES+=($i) done find /var/candy -name "chocolate_[0-9]" | while read snack do FILES+=($snack) done for file in ../out/amsterdam/...
7
votes
2answers
3k views

How Can I Expand A Tilde ~ As Part Of A Variable?

When I open up a bash prompt and type: $ set -o xtrace $ x='~/someDirectory' + x='~/someDirectory' $ echo $x + echo '~/someDirectory' ~/someDirectory I was hoping that the 5th line above would have ...
6
votes
2answers
2k views

Running commands stored in shell variables

The following works in my shell (zsh): > FOO='ls' > $FOO file1 file2 but the following doesn't: > FOO='emacs -nw' > $FOO zsh: command not found: emacs -nw even though invoking emacs -...
6
votes
4answers
6k views

How to use call-by-reference on an argument in a bash function

I am trying to pass a "var name" to a function, have the function transform the value the variable with such "var name" contains and then be able to reference the transformed object by its original "...