Convert multiline bash script to an one line
8,918
Parsing bash in oneliners is a hard task...
Anyway as a starting point, here goes a suggestion to cover very specific situations like the one presented
perl -p0e '
s/#.*//;
s/;?\s+(do|done|then|else|fi)\s+/ ; $1 /g '
Related videos on Youtube
Author by
snoop
Updated on September 18, 2022Comments
-
snoop over 1 year
I have script like this:
for f in * do #if condition if [[ -d $f ]]; then echo "$f is a directory"; else echo "$f is not a directory"; fi done
Is it possible to convert multiple script into 1 line like this? (maybe I need to delete
#
comment statement(s)).for f in *; do if [[ -d $f ]]; then echo "$f is a directory"; else echo "$f is not a directory"; fi done
I can change for statement syntax in above script like:
for f in *
for f in *;
for f in *;do
Same applies to
if
condition. In all the cases it should generate a proper 1 line. What could be the automated way to do this?-
muru over 8 yearswhat's the advantage? On the contrary, writing compound commands like this in one line actually harms readability.
-
snoop over 8 yearsYou are right, but case where automation is required needs 1 liner, instead of writing a large script.
-
snoop over 8 yearsIf you know about
plink
which is a commandlineputty
version works perfectly with command provided at commandline. I mean executing script compared with command is quite tedious and erroneous usingplink
. -
muru over 8 yearsIf it has problems with multi-line commands, then, no,
plink
doesn't work "perfectly". I have never had any problems with multiline commands using thessh
tool on Linux systems. -
snoop over 8 yearsI will give you another example, If you ever worked on networking devices such as Cisco Firewall, Cisco Router, Mipu Router etc. These type of N/W devices only understand commands, no script. Also, if we fire script on target machine its internally get copied somewhere on target system and for that it should have space.
-
muru over 8 yearsyou seem to have some serious confusion. There is a difference between a script and multi-line command. The former is a file, the latter is just a multi-line command. If the target system understands bash, it will understand multiline commands just fine. Do your Cisco devices understand bash? If no, what is the relevance of those to this question?
-
snoop over 8 yearsYes Cisco device understand it.
-
muru over 8 yearsThen they understand multiline commands.
-
terdon over 8 yearsYou realize that both the one-line version and the multiline version can be pasted directly into the terminal, right? Neither one of those is a script, they are both commands than can be run directly in the terminal.
-
snoop over 8 yearsYeah, writing generic program for this problem is difficult, but this is fine example for this situation.
-
nickchalkida over 8 yearsExecutes the awk command in quotes with input from script.txt. More from the awk manual ... I am busy ...