Questions tagged [variable-substitution]

The tag has no usage guidance.

Filter by
Sorted by
Tagged with
45
votes
1answer
17k views

Variable substitution with an exclamation mark in bash

I have the following lines in my .cfg bash script file DDF_SOURCE="siebel_DATA_DATE_FORMAT" DATA_DATE_FORMAT=${!DDF_SOURCE} how is ${!DDF_SOURCE} evaluated? It would be !siebel_DATA_DATE_FORMAT, ...
27
votes
4answers
86k views

Use a variable reference “inside” another variable

I'm sure it is relatively simple, I just don't know how to do it. #!/usr/bin/ksh set `iostat` myvar=6 I want to something like echo ${$myvar} which i want interpreted as ${$myvar} -> ${6} -> value
25
votes
4answers
21k 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 ...
24
votes
2answers
5k views

What does ${PATH:+:${PATH}} mean?

I recently noticed the following in my cygwin profile, more precisely: /usr/local/bin:/usr/bin${PATH:+:${PATH}} What does it mean? Why is not just $PATH? Is this an 'if $PATH exists then add :$PATH'?...
22
votes
7answers
25k views

Double and triple substitution in bash and zsh

Follow-up to the background part in this question. In bash I can use ${!FOO} for double substitution, in zsh ${(P)FOO}. In both, the old-school (hack-y) eval \$$FOO works. So, the smartest and most ...
17
votes
2answers
11k views

How to avoid space after bash variable in string?

I have a variable for color. I use it to set color to strings, by evaluating it inside the string. However, I need to include space after the name(so that the name doesn't contain part of the text). ...
15
votes
3answers
3k views

Does bash support back references in parameter expansion?

I have a variable named descr which can contain a string Blah: -> r1-ae0-2 / [123], -> s7-Gi0-0-1:1-US / Foo, etc. I want to get the -> r1-ae0-2, -> s7-Gi0-0-1:1-US part from the string. ...
15
votes
1answer
1k views

Why does variable expansion without $ work in expressions?

#!/bin/bash VALUE=10 if [[ VALUE -eq 10 ]] then echo "Yes" fi To my surprise, this outputs "Yes". I would have expected it to require [[ $VALUE -eq 10 ]]. I've scanned the CONDITIONAL ...
14
votes
4answers
39k 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 ...
13
votes
4answers
3k 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
4answers
4k views

${!FOO} and zsh

${!FOO} performs a double substitution in bash, meaning it takes the (string) value of FOO and uses it as a variable name. zsh doesn’t support this feature. Is there a way to make this work the same ...
12
votes
3answers
2k views

Is “${PS1-}” valid syntax and how does it differ from plain “$PS1”?

I am looking at a script that has: if [ "${PS1-}" ]; then That trailing - bugs me a bit because it doesn't seem to Posix or Bash standard syntax. It this some arcane syntax that has been around ...
12
votes
1answer
727 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=${...
12
votes
3answers
7k views

Dereference concatenated variable name

I can do this, but it requires making a string of the variable then dereferencing it. Is there any way to shorten it to a simpler statement? #!/bin/bash FRUITS="BANANA APPLE ORANGE" BANANA_COLOUR="...
11
votes
2answers
5k views

Bash variable substitution of variable followed by underscore

The variable BUILDNUMBER is set to value 230. I expect 230_ to be printed for the command echo $BUILDNUMBER_ but the output is empty as shown below. # echo $BUILDNUMBER_ # echo $BUILDNUMBER 230
11
votes
2answers
52k views

Passing a variable to sed [duplicate]

I cannot not use a shell variable in sed in the $NUMBER form. I have this line in my shell script: cat shared.txt sed 's/whatever1/$2 ... whatever2/' > shared2.txt The result in shared2.txt looks ...
10
votes
1answer
493 views

What does the substitution ${!var_name+x} mean?

I found a script that has a function that checks if a variable is set but i don't understand it very well. check_if_variable_is_set() { var_name=$1 if [ -z "${!var_name+x}" ]; then ...
10
votes
2answers
3k views

Append to PATH-like variable without creating leading colon if unset

I need to append a directory to PKG_CONFIG_PATH. Normally, I would use the standard export PKG_CONFIG_PATH=${PKG_CONFIG_PATH}:$(pyenv prefix)/lib/pkgconfig but PKG_CONFIG_PATH has not been ...
10
votes
3answers
4k views

Can command substitution be nested in variable substitution?

I would like to use variable substitution on a particular string that I access via a command. For example, if I copy something into my clipboard, I can access it like this. $ xclip -o -selection ...
9
votes
9answers
4k views

Bash: Extract one of the four sections of an IPv4 address

We can use the syntax ${var##pattern} and ${var%%pattern} to extract the last and first section of an IPv4 address: IP=109.96.77.15 echo IP: $IP echo 'Extract the first section using ${var%%pattern}: ...
9
votes
2answers
8k views

Grep to find the correct line, sed to change the contents, then putting it back into the original file?

I'm trying to change a single word on a specific line in a file, but I'm having some trouble connecting all together. Basically, on one line in my file there is a keyword 'firmware_revision', and on ...
9
votes
2answers
8k views

Piping bash string manipulation

I've read some other piping bash string manipulation questions but they seem to be specialized applications. Essentially, is there a way to do the below simpler? instead of $ string='hello world'; ...
9
votes
3answers
8k views

How can I pass argument stored on a variable to WGET

I'm writing a bash script that extensively uses wget. To define all common parameters in one place I store them on variables. Here's a piece of code: useragent='--user-agent="Mozilla/5.0 (Windows NT ...
8
votes
5answers
1k views

Using parameter substitution on a Bash array

I have file.txt that I need to read into a Bash array. Then I need to remove spaces, double quotes and all but the first comma in every entry. Here's how far I've gotten: $ cat file.txt 10,this 2 0 ...
8
votes
3answers
18k views

bash ${VAR//search/replace} and weird regex behaviour

I am trying to do some searching and replacing on a variable using the ${VAR//search/replace} parameter expansion. I have a pretty long and evil PS1, that I want to work out the size of after ...
8
votes
1answer
19k views

Executing commands with ssh and shell script using variables on a remote machine

I'd like to execute a command and script located on a remote machine with a script on a local machine. I know it's possible to execute these kind of commands with ssh, so I made: #!/bin/bash ssh ...
7
votes
4answers
36k views

Is there any way to print value inside variable inside single quote?

Consider I've set variable site and needs to be printed by echo or printf, but If I use single quote to write something and want to use variable then how? Example: $ site=unix.stackexchange.com $ ...
7
votes
2answers
1k views

calling other variables in a variable name (Bash)

At the moment I have the next paths langs="EN GE" dir_EN=/xx dir_GE=/zz As you can see the variable $langs has all possible languages in a single array. I would like to save all those paths in a ...
7
votes
2answers
24k views

Bash variable substitution in a JSON string

I'm trying to create a JSON in BASH where one of the fields is based on the result of an earlier command BIN=$(cat next_entry) OUTDIR="/tmp/cpupower/${BIN}" echo $OUTDIR JSON="'"'{"hostname": "...
7
votes
1answer
1k views

Append (alter) each array element via parameter expansion (i.e. without printf)?

Let the script below exemplify my quandary.. #!/bin/zsh STUFF=( moose-hoof ovary clydsedale ) echo ${MINE=$(printf "MY-%s " $STUFF)} echo ${MINE_EXP=${STUFF/^/MY-}} MY-moose-hoof MY-ovary MY-...
7
votes
1answer
651 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 ...
7
votes
1answer
782 views

Why is bash extended-globbing variable substitution acting at the byte level?

I thought that bash variable substitution and globbing worked at character resolution, so I was rather surprised to see it acting at the byte level. Everything in my locale is en_AU.UTF-8 When ...
7
votes
2answers
704 views

Any way to show each step during the command processing?

set -x just show a final result of the command. Any way to view each step more clear, like pics below.
6
votes
2answers
851 views

Why do here-documents attempt shell substitution even on a commented line?

I wanted to see how some ASCII art looked in terminal so: $ cat <<EOF ...
6
votes
3answers
561 views

Why is there a number in the zsh parameter expansion ${1-$PWD}

I have this script I'm basing my current script off of. I just don't understand why he has typeset result part dir=${1-$PWD} in there. I get the same result if I just write dir=$PWD. With typeset is $...
6
votes
1answer
1k views

Variable with colon dash ${VAR:-}

How does "${2:-}" work in an 'if-then-else example' below? Somehow I cannot help but think that being ${2:-} it means the second argument, but I am curious what the colon(:) and dash(-) after the ...
5
votes
2answers
779 views

How can I add datetime to an existing file name in Linux?

I want to add date and time to the file name, for example: 08032016out.log.zip This is what I try to do: _now=$(date +"%m_%d_%Y") _file="$_nowout.log" touch $_file.txt # creating new file with the ...
5
votes
1answer
1k views

Bash echo $-1 prints hb1. Why? [duplicate]

If I ask bash to echo the -1th argument it prints hb1: echo $-1 hb1 Why? What is it accessing?
5
votes
3answers
4k views

Spaces for variables in bash script

I have a space in one of the directory names. I want to list a file under it from a bash script. Here is my script: fpath="${HOME}/\"New Folder\"/foobar.txt" echo "fpath=(${fpath})" #fpath="${HOME}/$...
5
votes
3answers
15k views

Variable not expanding inside another variable bash

I am reading a csv file in bash script as follows: resource='/data/bscs/' while IFS='|'read seqid fname fpath do echo "FILENO: $seqid" echo "FILENAME: $fname" echo "...
5
votes
3answers
4k views

How to generate new var names on the fly

I'm trying to generate dynamic var names in a shell script to process a set of files with distinct names in a loop as follows: SAMPLE1='1-first.with.custom.name' SAMPLE2='2-second.with.custom.name' ...
5
votes
3answers
238 views

How to create a loop with five (5) input variables?

I have a proprietary command that requires five (5) inputs to properly execute the command. command -cval <value> -tval <value> -dval <value> -kval <value> I need to be able ...
5
votes
1answer
43k views

How to reassign new values to array elements?

I'm trying to figure out like three or four things at the same time.The most I need help with is how to get the greatest number in all the files that I have created on a prior run of my script, that ...
5
votes
2answers
1k views

How does Bash handle quoting in the string replacement section of parameter expansion?

Is there any consistent logic to it? some-command "${somevariable//some pattern/'how does this get parsed?'}" I've posted some conclusions and raw tests below as an "answer" but they're not a full ...
5
votes
2answers
7k views

using bash script to output new script: need mixture of variables to be replaced and not replaced

I'm having a problem with bash variable substitution. Here's a silly example of what I am trying to do. I need to output a new script from a bash script. A line (see echo in my example) has a mixture ...
5
votes
2answers
951 views

What is the effect of “${(@f)…}” in Zsh?

I ran into a Zsh script and wanted to know its meaning. In the scripts below there is ${$(@f)$(egrep "$2","$file")} expression. From what I searched, @ is to use represent all positional parameters, ...
5
votes
0answers
88 views

Correct treatment of quotes in parameter expansions

Using the default value of IFS, consider unset var set -- ${var:-"hello"} echo "$#" This prints 1 as the parameter expansion expands to the single string hello. unset var set -- "${var:-"hello"}" ...
4
votes
4answers
4k views

Backslash in variable substitution in Bash

I was working on a Bash script to help partition a hard drive correctly, and I came across a strange problem where I had to append a number to a variable. It took me a while to get the outcome right ...
4
votes
1answer
571 views

readlink literal vs variable

Using BASH: the answer is probably obvious but, not for me. > echo $PWD /root/fcm > readlink -f ~ /root > # but then with a variable or literal > a='~' > readlink -f $a /root/fcm/~ >...
4
votes
4answers
4k views

Can I reload variable in a watch command?

Part of my job involves some data handling. One of the tasks is to 'flatten' a set of directories (which we'll call Dir for now), and copy them to a new location called DirFlat. This can take a long ...