Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set variable in Bash script to contents of file plus some text after

Tags:

bash

How do I set a Bash variable in a shell script in redhat Linux to the contents of a file, which is only one line, and then add some text after it.

For example:

echo "Version 1.2.3.4" > $TMPDIR/devver
env=dev
export ${env}_result="`cat $TMPDIR/${env}ver` (No response - version is from cache)"
echo $dev_result

I want the output to be:

Version 1.2.3.4  (No response - version is from cache)

Instead, I get a newline after the version, like this:

Version 1.2.3.4
(No response - version is from cache)
like image 807
David Avatar asked Jan 29 '26 19:01

David


2 Answers

Your problem isn't in the variable setting it is in the file creation. echo appends a newline to the file contents. So use

echo -n "Version..."

and things should work.

like image 155
DrC Avatar answered Feb 01 '26 13:02

DrC


Use a bash builtin:

export ${env}_result="$(< $TMPDIR/${env}ver) (No response - version is from cache)"
echo "$dev_result"

Documented here: "The command substitution $(cat file) can be replaced by the equivalent but faster $(< file)."

like image 29
glenn jackman Avatar answered Feb 01 '26 13:02

glenn jackman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!