I am trying to define and use alias within bash -c with a one-line command.
The command:
bash -c "eval $'df'"
works fine, but:
bash -c "eval $'alias df5=df\ndf5 -h'"
doesn't. Why, and how can I define and use alias within bash -c with a one-line command?
From Kusalananda's answer on how can I write an eval command containing a new line into one line?:
"The
$'...'is a "C string", andbashwould expand the\nwithin it to a literal newline before passing it toeval.
Therefore my understanding is that one has to use ' within the eval. Additionally, since the Bash manual says:
Enclosing characters in single quotes (
') preserves the literal value of each character within the quotes. A single quote may not occur between single quotes, even when preceded by a backslash.
My understanding is that one should use " outside the eval, since there is ' inside the eval.
Comments:
- See How can I write an
evalcommand containing a new line into one line? for the explanation of the use of\ninstead of; - The motivation behind the question is that in my actual entire command, I use the aliased command for other things (the command looks like
docker run -it ubuntu:18.04 bash -c "eval $'alias pip=pip3\nsource blah.sh; exec bash"). whereblah.shusespip. The full actual command is:docker run --interactive --tty ubuntu:18.04 bash -c "apt update; apt install -y git nano wget htop python3 python3-pip unzip; git clone https://github.com/KhalilMrini/LAL-Parser; cd LAL-Parser/; alias pip=pip3; source requirements.sh; apt-get install -y libhdf5-serial-dev; alias python=python3 ; source parse.sh; exec bash", but I need to addevalaroundalias. The command launches a Docker container, installs some requirements and runs some Python code. - The command is aimed for a non-technical colleague: I'd prefer them to run just a one-line command so that it's easy for them to use. As a result I'd prefer not to have to require a file (e.g., a
Dockerfileorbashscript) for the command to work. The following command:
bash -c " eval 'alias df5=df df5 -h' "as well as the command
bash -c " alias df5=df df5 -h "also don't work. Error
bash: line 2: df5: command not found. As a result it seems that the issue is thataliasdoesn't work withinbash -c. I don't know why and wonder whether there is some workaround.