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 ...
23
votes
3answers
12k 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':...
58
votes
5answers
84k 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 ...
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?
104
votes
3answers
58k 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}}' \{\} \...
394
votes
3answers
280k 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 ...
4
votes
2answers
341 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 ...
64
votes
12answers
150k 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
17k 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 "$...
84
votes
6answers
239k 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: ...
18
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 ...
10
votes
4answers
23k 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 ...
9
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 ...
6
votes
1answer
453 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: ...
33
votes
2answers
47k views

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

If I'm assigning a variable with temp=$! what would it be its value?
11
votes
2answers
44k 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 ...
2
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 ...
13
votes
2answers
8k 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='.*': ...
9
votes
3answers
2k 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
4k 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 ...
1
vote
3answers
17k 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 ...
11
votes
2answers
42k 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 ...
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
896 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?
4
votes
3answers
1k views

Unable to assign output of nested commands to variable in bash

I was trying to assign below command(which choose the random line from file) to a variable, but not working. givinv@87-109:~$ head -$((${RANDOM} % `wc -l < file` + 1)) file | tail -1 cower givinv@...
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 ...
3
votes
3answers
4k 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
1answer
284 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?
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 ...
2
votes
1answer
10k 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: " { ...
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
687 views

grep misreads pattern from variable

I have a problem with escaped pattern put in grep. My test file is: export_cc = ${dir}/aaa/bbb/ccc export_cc = ${dir}/aaa/bbb/eee export_cc = ${dir}/aaa/bbb/ddd export_cc = ${dir}/aaa/bbb/fff ...
1
vote
2answers
167 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
1answer
207 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 ...
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/ /...
0
votes
0answers
36 views

Complex nested for loop in directory

I have two sets of files in two separate directories organized as such: #first directory /direc1/files file0.num1.tar.gz file0.num2.tar.gz file0.num3.tar.gz file0.num4.tar.gz . . . ...
-1
votes
2answers
55 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 ...
48
votes
9answers
179k 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
614 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 ...
16
votes
3answers
81k 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
948 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
74k 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
20k 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/...