Tech/SmallBashTricks

From ~esantoro
Revision as of 13:35, 17 August 2024 by Esantoro (talk | contribs) (Created page with "I've been writing shell scripts for many years now and every now and then I get to learn new more or less neat tricks when using bash. In this page I want to collect tricks i find over time. == Unquoted heredocs == You occasionally want to write multi-line strings to files whose syntax may or may not be bash-compatible. Heredocs works great usually, until the content of your multi-line strings contain something bash might want to evaluate:<syntaxhighlight lang="shell-s...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

I've been writing shell scripts for many years now and every now and then I get to learn new more or less neat tricks when using bash.

In this page I want to collect tricks i find over time.

Unquoted heredocs

You occasionally want to write multi-line strings to files whose syntax may or may not be bash-compatible. Heredocs works great usually, until the content of your multi-line strings contain something bash might want to evaluate:

manu@astrolabio:/tmp$ cat > /tmp/somefile <<EOF
you're not supposed to substitute stuff, but:

$(date)
pwd is $PWD
EOF
manu@astrolabio:/tmp$ cat somefile 
you're not supposed to substitute stuff, but:

sab 17 ago 2024, 15:33:29, CEST
pwd is /tmp
manu@astrolabio:/tmp$

Turns out that if you single-quote your EOF string, no substitution will be performed:

manu@astrolabio:/tmp$ cat > /tmp/somefile <<'EOF'
you're not supposed to substitute stuff, but:

$(date)
pwd is $PWD
EOF
manu@astrolabio:/tmp$ cat somefile 
you're not supposed to substitute stuff, but:

$(date)
pwd is $PWD
manu@astrolabio:/tmp$


If anybody is wondering where i'd use this... I'm drafting some terraform infrastructure code and i'm setting screen default settings on a ops box via cloud-init user-data... Yeah.