alistaircol
alistaircol

Reputation: 1453

Bash alias a command with backtick/executable part (escape backticks)

I have made a simple bash command to clear caches in Laravel:

for w in `php artisan | grep 'clear' | awk '{print $1;}'`; do php artisan $w; done

I would like to add this as an alias, e.g. I just do laravel-cache. I ran:

alias laravel-cache="for w in `php artisan | grep 'clear' | awk '{print $1;}'`; do php artisan $w; done"

thinking this would add an alias, but when running alias to see them, I found:

# alias
alias egrep='egrep --color=auto'
alias fgrep='fgrep --color=auto'
alias grep='grep --color=auto'
alias l='ls -CF'
alias la='ls -A'
alias laravel-cache='for w in clear-compiled
auth:clear-resets
cache:clear
config:clear
route:clear
view:clear; do php artisan view:clear; done'
alias ll='ls -alF'
alias ls='ls --color=auto

but obviously this didn't work:

# laravel-cache
bash: syntax error near unexpected token `auth:clear-resets

So, my question would be how do you escape the backtick (or executable part to execute when the alias is run and not when it is added)?

Upvotes: 2

Views: 497

Answers (1)

l'L'l
l'L'l

Reputation: 47169

You should probably be creating a function instead of an alias:

Single Line

laravel-cache () { for w in $(php artisan | grep 'clear' | awk '{print $1}'); do php artisan "$w"; done ; }

Formatted

laravel-cache () { 
  for w in $(php artisan | grep 'clear' | awk '{print $1}') 
    do
      php artisan "$w"
  done ;
}

Generally whenever doing more than just changing the default options of the command (eg. piping to additional command(s)) it's recommended to use a function.

You can add this to your ~/.bash_profile for example and then use it similarly to an alias. Once added to your profile simply source it and you should be ready to use the command:

$ source ~/.bash_profile

Upvotes: 4

Related Questions