Context:
I want to run a command stored in a variable in bash.
My bash file:
#!/bin/bash # ----------------------------------------------- # --- COMMANDS --- # --- Vanilla style --- # ----------------------------------------------- GRUNT="node_modules/grunt-cli/bin/grunt" LS="ls" # ----------------------------------------------- # --- COMMANDS --- # --- Using Docker --- # ----------------------------------------------- GRUNT="docker exec compose_custom-node_1 node_modules/grunt-cli/bin/grunt" LS="docker exec compose_custom-node_1 ls" # *********************************************** # *** Execution *** # *********************************************** # ----------------------------------------------- # Compile SCSS using Grunt # ----------------------------------------------- echo "Building CSS from Sass files..." echo "$(docker exec compose_custom-node_1 ls -l)" echo "$($LS -l)" $($GRUNT sass)
Problem:
When I run this bash file, the grunt sass
command throws an error:
mybash.sh: line 25: $'E[4mRunning' : command not found
Whole return of my bash:
darckcrystale@kermit:/var/www/my_folder$ ./my_bash.sh Building CSS from Sass files... total 188 -rw-rw-r-- 1 node node 3627 May 2 19:00 Gruntfile.js drwxr-xr-x 282 root root 12288 May 3 12:12 node_modules drwxr-xr-x 4 node node 4096 May 2 18:39 sass total 188 -rw-rw-r-- 1 node node 3627 May 2 19:00 Gruntfile.js drwxr-xr-x 282 root root 12288 May 3 12:12 node_modules drwxr-xr-x 4 node node 4096 May 2 18:39 sass my_bash.sh: ligne 25: $'E[4mRunning' : commande introuvable
Investigation:
The commands echo "$(docker exec compose_custom-node_1 ls -l)"
and echo "$($LS -l)"
seem to work, but not the $($GRUNT sass)
.
If I run docker exec compose_custom-node_1 node_modules/grunt-cli/bin/grunt
in a terminal, I see this output:
Running "sass:app1" (sass) task Running "sass:sticky-app2" (sass) task Done, without errors.
Question:
Do you have a clue for me? What I am doing wrong?
Advertisement
Answer
Better to use a function to store complex commands than a variable,
grunt() { docker exec compose_custom-node_1 node_modules/grunt-cli/bin/grunt "$@" }
and call this as just
grunt "saas"
wherever needed in your script. See BashFAQ-050 which talks about this exact requirement on complex cases.