Wednesday, April 13, 2022

[SOLVED] $_ in bash vs. dash scripts

Issue

I need to port a short script from bash to dash (i.e. sh under Debian 10). It contains the following line:

chown root:www-data /etc/nginx/conf.d && chmod 775 $_

This now fails because $_ held the previous command's last argument (i.e. /etc/nginx/conf.d) with bash but now holds a different value with non-interactive dash. As another case in point, outputs from bash -c 'echo 1 2 && echo $_' and dash -c 'echo 1 2 && echo $_' also differ.

What is a typical way for forming "concise" statements of the above type in dash (without resorting to more specialized commands, such as install)?


Solution

Just write a function.

chownmod () { chown "$1" "$3" && chmod "$2" "$3"; }

And replace the line with the following.

chownmod root:www-data 775 /etc/nginx/conf.d


Answered By - ceving
Answer Checked By - Dawn Plyler (WPSolving Volunteer)