Reputation: 1379
In shell script how to make script read commands in input file string
a="google.analytics.account.id=`read a`"
echo $a
cat script2.sh
a=`head -1 input.txt`
echo $a
input.txt
google.analytics.account.id=`read a`
If I run script1.sh
the read
command is working fine, but when I am running script2.sh
, the read
command is not executed, but is printed as part of the output.
So I want script2.sh to have the same output as script1.sh.
Upvotes: 0
Views: 320
Reputation: 999
In script1.sh the first line is evaluated, therefore the read a
is executed and replaced in the string.
In script 2.sh the first line is evaluated, therefore the resulting string from execution of head
is put into the variable a.
There is no re-evaluation done on the resulting string. If you add the evaluation with eval $a
and the first line in input.txt is exactly as the first line of script1.sh (actually the a="..."
is missing) then you might get the same result. The heredoc, as CharlesDuffy suggested, seems more accurate.
Upvotes: 0
Reputation: 295650
Your input.txt
contents are effectively executed as a script here; only do this if you entirely trust those contents to run arbitrary commands on your machine. That said:
#!/usr/bin/env bash
# ^^^^- not /bin/sh; needed for $'' and $(<...) syntax.
# generate a random sigil that's unlikely to exist inside your script.txt
# maybe even sigil="EOF-$(uuidgen)" if you're guaranteed to have it.
sigil="EOF-025CAF93-9479-4EDE-97D9-483A3D5472F3"
# generate a shell script which includes your input file as a heredoc
script="cat <<$sigil"$'\n'"$(<input.txt)"$'\n'"$sigil"
# run that script
eval "$script"
Upvotes: 1