Sometimes I need to exec a single command which is in a shell script.
I already know sed -n 'line_num p' can print that line. But how can I exec that printed out specific line as a command?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Try this:
sed -n 'line_num p' | bash
or, if the command does not contain whitespace,
"$(sed -n 'line_num p')"
Method 2
If you’re doing this interactively, you could write the line into the bash history:
history -s "$(sed -n 'line_num p')"
Then press ↑Enter to insert the line into the readline buffer, and execute it; that gives you a chance to glance at the line before it’s too late.
Method 3
You can do…
{ head -n"$((NUM-1))"; IFS= read -r line; } </path/to/script >/dev/null
eval "$line"
That will get only the $NUM line from your script in the shell variable $line and then evaluate it as a command in the current shell.
Another way to do this could look like:
</path/to/script sed "${NUM}q;d" >/tmp/"$$"
. /tmp/"$$" ; rm /tmp/"$$"
Method 4
Are you editing your script with vim (vi on Linux)?
In vi add a mapping:
:nmap <F4> Y:!<C-R>"<C-H><CR>
and afterwards when you are on the interesting line in vi press F4
Method 5
In bash you can run the following command:
for line in $(cat file.txt); do command $line; done
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0