How to assign string outputs of expressions in variables without echo? [duplicate] - bash

This question already has answers here:
How to pass the value of a variable to the standard input of a command?
(9 answers)
Closed 1 year ago.
I am currently saving string outputs from expressions like so
SOME_PATH="/some/path/file"
FILE_NAME=`echo "$SOME_PATH" | rev | cut -f 1 -d "/" | rev )`
FILE_FOLDER=`echo "$SOME_PATH" | sed s/$FILE_NAME//`
echo ${SOME_PATH}
echo ${FILE_NAME}
echo ${FILE_FOLDER}
which seems like the echo is superfluous, but I couldn't get it to work without it. What is the preferred way?

What is the preferred way?
The preferred way is to use variable expansions.
somepath='/some/path'
filename=${somepath##*/}
dirname=${somepath%/*}
Also: do not use backticks `, prefer $(...), quote variable expansions "s/$FILE_NAME//", prefer to use lower case variables for local variables and check your scripts with shellcheck.
How to assign string outputs of expressions in variables without echo?
Use here string to save one fork() call.
var=$(<<<"$var" command)

Related

Applying sed in bash variable and assigning it to another [duplicate]

This question already has answers here:
Concat numbers from JSON without doublequotes using jq [duplicate]
(1 answer)
How to remove double-quotes in jq output for parsing json files in bash?
(2 answers)
Closed 1 year ago.
I have:
MY_FOLDER=`jq '.results_folder' ./conf.json`
FOLDER_WITHOUT_QUOTES=$MY_FOLDER | sed 's/"//g'
python my_code.py > $FOLDER_WITHOUT_QUOTES/log.log
So, there is a json file with a folder name. But jsons demand strings to be inside ". And reading the json with bash returns me ", which I want to remove
Passing it to a variable and then applying sed isn't working. What's the correct syntax for doing it?
Thank you!
Posix shell would need:
FOLDER_WITHOUT_QUOTES="$(printf '%s\n' "$MY_FOLDER" | sed 's/"//g')"
With Bash you can use the here-document syntax:
FOLDER_WITHOUT_QUOTES=$(sed 's/"//g' <<< "$MY_FOLDER")
... and you can even get rid off a call to sed with the special substitution:
FOLDER_WITHOUT_QUOTES=${MY_FOLDER//\"}
Note: prefer the $(command) syntax to the backquotes which are less readable and cannot be nested as easily.

Setting a variable and utilizing sed [duplicate]

This question already has answers here:
Replace one substring for another string in shell script
(16 answers)
Closed 4 years ago.
I've been trying to wrap my head around this for over an hour now and my searches haven't helped yield the answer.
Trying to set a variable inside a bash script. This variable is taking variable-A and removing variable-B from it.
Prefix="$(echo ${Process} | sed -e 's/${Server}//g')"
So if Process=abcd1wxyz01 and Server=wxyz01, then Prefix should end up being abcd1.
I've tried so many iterations from online searches I honestly can't recall what all I've tried.
Your problem are the quotes, as pointed out in afsal_p's answer.
You could do this with parameter expansion instead:
$ process=abcd1wxyz01
$ server=wxyz01
$ prefix=${process%"$server"}
$ echo "$prefix"
abcd1
The ${word%suffix} expansion removes suffix from the end of word.
please use " instead of ' while using bash variables inside sed:
Prefix="$(echo ${Process} | sed -e "s/${Server}//g")"
echo $Prefix

Assigning the output of a bash string manipulation to a variable [duplicate]

This question already has answers here:
How do I set a variable to the output of a command in Bash?
(15 answers)
Closed 5 years ago.
On Ubuntu 16.04, I have a bash script which I run as root. I want to remove all spaces from the user's input, and assign the trimmed string to a variable.
read -p "Enter username: " USERNAME
echo "$USERNAME" | sed s/' '/''/g
TRIM="$USERNAME" | sed s/' '/''/g
echo $TRIM
echo "Done"
Here's some sample input and output:
Enter username: h j k l
hjkl
Done
$TRIM is empty.
What change do I need to make to get $TRIM to contain the result?
Use $() to capture the output of a command.
trim=$(echo "$USERNAME" | sed 's/ //g')
However, you don't need a command for this, you can use the bash parameter expansion operator to do substitution.
trim=${username// /}
P.S. Don't use uppercase variable names, they're conventionally reserved for environment variables.
There are a couple of things you should note with your script.
First of all, uppercase identifiers like USERNAME are usually reserved for environment variables. So you might well override a shell variable accidentally that causes undesired effects. Same is the case with TRIM.
Secondly, you should check the default shell in your Ubuntu distribution using the SHELL built-in. Do something like
echo $SHELL
If the output is dash or bash, you could use command substitution to achieve your objective.
trim=$(echo "$username" | sed 's/ //g')
Mind that the sed commands themselves should be put under the single quotes.
When you echo trim, use double quotes to prevent word splitting like
echo "$trim" # In your case though the double quotes doesn't make any difference

Shell variable unexpected empty in if-then statement after calling sed [duplicate]

This question already has answers here:
How to pass the value of a variable to the standard input of a command?
(9 answers)
Closed 1 year ago.
I have a shell script:
TOPDIR=`pwd`
FOLDER=$($TOPDIR | sed 's/\//\_/g')
if [[ condition ]];then
source ~/[$FOLDER]-build/build-env.sh
fi
the TOPDIR here is /home/uname/project, so the variable FOLDER is supposed to be _home_uname_project because sed is called to replace / with _.
But it goes wrong when executing, terminal tells that /home/uname/[]-build/build-env.sh: No such file or directory which, I guess, means that FOLDER is unexpected empty in the if-then statement. Can anybody help me with figuring this out?
If you look at the output of just
$TOPDIR | sed 's/\//\_/g'
you'll realize that it's empty; it's trying to execute a command equal to the contents of $TOPDIR and pipe the output of that into sed, but there is no output in the first place.
You could do
pwd | sed 's\//_/g'
instead (no need to escape _), which would work.
Or, instead of using an external tool, you could use parameter expansion
topdir="$(pwd)"
topdir="${topdir//\//_}"
with the same result.
Notice that uppercase variable names are discouraged, as they're more likely to clash with existing, reserved names.

multiple substitutions on a string in bash [duplicate]

This question already has answers here:
Can ${var} parameter expansion expressions be nested in bash?
(15 answers)
Closed 7 years ago.
I have a variable named inet which contains the following string:
inet="inetnum: 10.19.153.120 - 10.19.153.127"
I would like to convert this string to notation below:
10.19.153.120 10.19.153.127
I could easily achieve this with sed 's/^inetnum: *//;s/^ -//', but I would prefer more compact/elegant solution and use bash. Nested parameter expansion does not work either:
$ echo ${${inet//inetnum: /}// - / }
bash: ${${inet//inetnum: /}// - / }: bad substitution
$
Any other suggestions? Or should I use sed this time?
You can only do one substitution at a time, so you need to do it in two steps:
newinet=${inet/inetnum: /}
echo ${newinet/ - / }
Use a regular expression in bash as well:
[[ $inet =~ ([0-9].*)\ -\ ([0-9].*)$ ]] && newinet=${BASH_REMATCH[#]:1:2}
The regular expression could probably be more robust, but should capture the two IP addresses in your example string. The two captures groups are found at index 1 and 2, respectively, of the array parameter BASH_REMATCH and assigned to the parameter newinet.

Resources