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)
1,210
questions
0
votes
2
answers
66
views
how to replace a string with a variable?
I am trying to write a script containing a loop that enters a series of directories containing the same file, to replace a text string in a file with a variable that matches the directory's name.
The ...
34
votes
3
answers
30k
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 ...
4
votes
2
answers
381
views
Issue expanding variable with multiple wildcards in bash shell script with mv / rename
I wrote a bash shell script for Linux to move files in a static folder according to parameters specified in a data file.
I've reduced that script to a minimal reproducible example to demonstrate an ...
0
votes
1
answer
29
views
How to integrate multiple inline `if` variable checks into `configure` flag selection
I'm compiling Nginx from source on Debian 12 in Bash. I'd like to select the TLS vendor (e.g. LibreSSL, OpenSSL) via a preflight variable ($nginx_tls_vendor). An example configure command without the ...
0
votes
1
answer
53
views
value of $VAR already contains backtick and/or single quote inside. How to handle it? How to properly pass $VAR to program? [duplicate]
$ bash --version
GNU bash, versione 5.2.26(1)-release (x86_64-pc-linux-gnu)
I don't know how to deal with $VAR when its value inside contains single quote (') and/or backtick (`).
I'm in the need of ...
4
votes
1
answer
291
views
How can I pass variables to a file printed from outside a bash script?
Assuming I have a variable v="c d e f g" and a file with the content:
line1
$v
line3
How can I make a bash script print this file with the content of the variable in line 2 as if I was ...
14
votes
3
answers
10k
views
Capture the output of a shell function without a subshell
I have rbenv (ruby version manager) installed on machine and it works like that:
$ rbenv local
2.3.1
Writing to stdout the local version of my ruby. I want to rescue this version and declare it in a ...
22
votes
4
answers
133k
views
Setting variables from shell: how to use them in a script?
How can I set variables to be used in scripts as well? They don't have to be global / system-wide, just the current session is sufficient. But for some reason they seem gone even if I run a script ...
63
votes
7
answers
151k
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 ...
0
votes
1
answer
62
views
Bash brace expansion doesn't work in an export statement
Consider the following example:
$ echo file_{a,b,c}
file_a file_b file_c # brace expansion worked :)
$ export VARIABLE=file_{a,b,c}
$ echo $VARIABLE
file_c # brace ...
20
votes
6
answers
939
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&...
4
votes
1
answer
3k
views
Where are Kernel global variables stored?
I am currently writing a Linux kernel module. I am aware that in case of userspace programs, uninitialized global variables (exported to other modules using EXPORT_SYMBOL) are stored in BSS segment ...
77
votes
8
answers
167k
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?
655
votes
4
answers
499k
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 ...
63
votes
6
answers
144k
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"
8
votes
4
answers
1k
views
Globbing shell variable names
I need to expand some shell (not environment) variable names that are thematically related, e.g. B2_... where ... could be one or more different things like ACCOUNT_ID, ACCOUNT_KEY, RESPOSITORY and so ...
0
votes
4
answers
2k
views
create variables from CSV with varying number of fields
Looking for some help turning a CSV into variables. I tried using IFS, but seems you need to define the number of fields. I need something that can handle varying number of fields.
*I am modifying my ...
3
votes
1
answer
3k
views
lifetime and validiy of exported variables in bash script
I have created a bash script to run some other programs with customized environment variables. Here is my first script named run-hello.sh in /home/user
#!/bin/bash
export PATH=$PATH":/home/...
1
vote
1
answer
95
views
Why does -n with unquoted variable containing empty string return true? [duplicate]
From man bash:
-n string
True if the length of string is non‐zero.
Examples:
# expected
$ var=""; [ -n "$var" ]; echo $?
1
# unexpected?
$ var=""; [ -n $var ]; echo ...
5
votes
2
answers
715
views
Is it while loop or the pipe causing global variable behaving unexpectedly
Could please someone explain the (from my POV) strange behavior of the COUNTER variable in the following code?
#!/bin/bash
COUNTER=0
function increment {
((COUNTER++))
}
function report {
...
189
votes
6
answers
287k
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?
$ abc='ls -l "/tmp/test/my dir"'
$ $abc
ls: cannot access '"/tmp/test/my': No ...
1
vote
0
answers
39
views
Why does `$PS1` sometimes include the bell, `\a`? [duplicate]
In Ubuntu 18.04 and 22.04 (WSL), I've noticed that $PS1 contains a "bell" character, \a:
$ echo $PS1
\[\e]0;\u@\h: \w\a\]${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\...
1
vote
3
answers
60
views
sed: update 2 similar variables in a file but keep the upper and lowercase
I have 2 variables in a file like below that I need to assign a new value inserted by one user input: read -p "Enter CName Name : " CName
sid=C02SBX
SID=C02SBX
When I run the following ...
-1
votes
1
answer
74
views
Is the following `readonly` use POSIX-ly correct?
I defined the following as read-only:
readonly root_command='sudo -s'
later used in my script as in:
exec $root_command
My question is, maybe I am slow or something, but I do not fully understand ...
0
votes
1
answer
94
views
How to assign null to or unassign a Bash variable if parameter is set?
Variable USE_TLS is to be unset, null, or empty when TLS is not to be used, but set to 1 when TLS must be enforced. I require it to be enforced by default (i.e., set), but not if I specify another ...
0
votes
0
answers
48
views
I want to issue "sudo su - <user>" to create a login shell, and pass an environment variable into the new shell [duplicate]
Oracle linux 7.9. Shell is bash.
I log in as user bob. From there I sudo to user sam and do my work. But I want to pass a variable into sam's new login shell.
So for example, this is what I currently ...
1
vote
0
answers
78
views
diff two multilines bash variables to list what lines aren't in the other
I've created a bash script that
Lists the document IDs I've put in an Elastic index, in $liste_ids_lines:
a004-événements-examen_individus_localisés_ou_non
a020-les_points-leurs_indicateurs-...
1
vote
2
answers
115
views
Redirect to a filename that will be a variable and contain a command substitution
I'm using nmap to scan a network and then create an XML file that contains the scanned information. I want that XML file to contain the date of the scan so that each file is unique and I can see the ...
1
vote
1
answer
191
views
Change hostname with a variable with for loop
I am trying to change the "hostname --transient" to some computers with a for loop using a variable. I want it to collect the "hostname -f" from the server itself and, using the ...
0
votes
1
answer
100
views
Using awk -v with Shell variable works great and prints to terminal, but when redirect to a file only the 1st record prints to the file
I am reading a file with a matching pattern then getting the first five lines after the matching pattern. The patterns are not in proper numeric order, so I am using a numeric variable in the pattern ...
1
vote
1
answer
162
views
some_variable vs some-variable in zsh
Why is it that zsh seems to understand what to do with some_variable=1 command, but not some-variable=1 command? E.g.: $ fs_screen=1 mpv --fs-screen=${fs_screen} someFile.mp4 works fine but $ fs-...
0
votes
1
answer
204
views
bash: string variable contains asterisk. how to use this variable for searching etc with grep, sed?
Have a nice day
I have got text file (zz.txt):
Chemical name
3-Aminopropane-1-sulphonic acid
Synonym(s)
--
Homotaurine * Tramiprosate
--
Chemical name
Common name and synonyms
...
I have variable
s=&...
0
votes
1
answer
51
views
Bash script variable syntax: with some commands it works, with others it does not [duplicate]
I do not understand the behaviour of this variable:
SSH_CONFIG_FILE="~/.ssh/config"
echo $SSH_CONFIG_FILE
ls -l $SSH_CONFIG_FILE
ls -l ~/.ssh/config
This is the output:
~/.ssh/config
ls: ...
46
votes
3
answers
35k
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='.*':
...
0
votes
2
answers
223
views
Use SED to replace part of a current variable with user input variable
I'm trying to replace only part of the existing variable with a new user input variable as below:
#Current Variable:
gdbName=Test.MY.DOMAIN.COM <--I need to replace the "Test" (This can ...
24
votes
1
answer
4k
views
What is the difference between $path and $PATH (lowercase versus uppercase) with zsh?
In FreeBSD 12, using the zsh shell, I noticed this difference when looking at $path (lowercase) versus $PATH (uppercase).
echo $path
/sbin /bin /usr/sbin /usr/bin /usr/local/sbin /usr/local/bin /...
20
votes
2
answers
12k
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 ...
1
vote
0
answers
205
views
Extract from a curl its dire failure message (if case of return code != 0), status code, output, and error message into four different variables
I need to extract from a curl emitted:
the bash error message coming with a non-zero ?$ return code, in case my command would direly fail
the http status code returned by the server contacted
the ...
3
votes
5
answers
11k
views
Is it a good practice to delete all variables at the end of a script?
Is it good to delete the variables used in a shell-script at the end of a script.
rm -rf $abc
rm -rf $def
or
unset $abc
unset $def
and so on.
Is this actually a good practice?
4
votes
2
answers
1k
views
How do I reliably capture the output of `ls` in this script?
The following script, play_movie.sh is meant to automatically select a movie if there is only one in the current directory and play it with ffplay. Otherwise it is meant to display a selection of ...
2
votes
3
answers
4k
views
Variable expansion inside parentheses and quotes
In the script below, I can't seem to make $var1 expand in the second statement. I've tried $var1, ${var1}, echo $var1 and '$var1'. It is inside a few sets of quotes and parentheses which I guess is ...
0
votes
2
answers
214
views
How to grep for the value of a variable inside a shell script?
I have 2 files:
a file full of values I want to look for
my source text file
I wrote a short shell command to loop thru my list of values and grep against my source file. If it doesn't find the ...
2
votes
1
answer
8k
views
How to read a file with two columns into a script so that each line read as two variables
I have a file that has two columns like such.
cat test.txt
100 2007
FFF 1993
7E7 1994
4BB 1995
I need to input each of the lines into a script, and have the two columns assigned as separate ...
0
votes
3
answers
70
views
How to expand variable inside single or double qoutes
I have 2 systems and they have the same directory strcuture. I want to execute a couple of commands on local system and the same on remote system.
I use the wildcards so when I have a new version of ...
0
votes
1
answer
102
views
How to store command with option on variable of a function in zsh?
I'm trying to learn bash scripting using freeCodeCamp tutorial for beginners on YouTube.
I'm stuck at the point where he shows how to create a function.
He saved on a variable a command with an option
...
-4
votes
1
answer
52
views
How to protect variable name inside shell arithmetic?
Variables can be protected with curly braces.
Mynewvar=1
echo $Mynewvar
1
echo ${Mynewvar}
1
However I can no longer protect them when inside shell arithmetic.
Mynewvar=1
echo $((Mynewvar+9))
10
echo ...
1
vote
0
answers
82
views
Can you assign a default array to a variable by specifying its values explicitly?
I know that I can use an existing array as the default value for a variable that is potentially uninitialized via
default_values=(1 2 'value is a string')
array=("${array[@]-${default_values[@]}}&...
3
votes
2
answers
5k
views
wget with URL variables?
I want know if I can use variables inside the url used by wget?
I'm trying to recreate in BASH:
I currently have:
WK_ARTIST="$(echo $ARTIST | sed 's/\ /\_/g' )"
WK_ALBUM="$(echo $ALBUM |...
28
votes
6
answers
5k
views
How to temporarily save and restore the IFS variable properly?
How do I correctly run a few commands with an altered value of the IFS variable (to change the way field splitting works and how "$*" is handled), and then restore the original value of IFS?
...
-4
votes
2
answers
218
views
Is it possible for any shell to interpret a string with decimal point as a number (int, float)?
This idea came to me with recent updates to Visual Studio Code, in which I usually shellcheck my code automatically as well. This is what I see, so you can get the idea:
This question is very simple ...