Home » Questions » Computers [ Ask a new question ]

error when using commandline as a bash alias on linux

error when using commandline as a bash alias on linux

I want to save the following commandline sequence as a bash alias:

Asked by: Guest | Views: 49
Total answers/comments: 2
Guest [Entry]

"Frankly, by the time a command gets that big, I'd make it into a script and not an alias. One advantage of a script is that you make it work with more files than just 'access.logs'.

That command sequence involves both single quotes and back-quotes - that always adds to the fun. Generally, you are better off using $(command args) in place of back-quotes.

When you use the double quotes around the alias, the back-quoted commands are executed as the alias is created - unless the shell has a different way of interpreting things when they define the alias. Also, $var expressions are evaluated inside double quotes, so your awk errors show that you have no arguments in the current shell.

So, if you must use an alias, then you probably need to use single quotes around the whole expression, plus for each single quote that appears in the expression, replace it with the sequence quote-backslash-quote-quote: '\''. The first quote terminates the current quoted string; the backslash quote represents a literal quote; the final quote restarts the quoted string.

That leads to:

alias downloads='grep `date '\''+%d/%b/%Y'\''` access.logs |
egrep 2765330645ae47d292c9ceac725d744e.py |
awk '\''{print $1, $4, $5, $7, $8, $9, $10}'\'' |
sort | uniq -c -w15 | sort -n'"
Guest [Entry]

"Since the alias is defined within double quotes, the date command gets executed at the time of definition of the alias, and the $1 variables get expanded too. You can check this by looking up the alias after you define it:

$ alias downloads=""grep `date '+%d/%b/%Y'` access.logs | egrep 2765330645ae47d292c9ceac725d744e.py |awk '{print $1, $4, $5, $7, $8, $9, $10}' | sort |uniq -c -w15 |sort -n""
$ alias downloads
alias downloads='grep 27/Sep/2009 access.logs | egrep 2765330645ae47d292c9ceac725d744e.py |awk '\''{print , , , , , , 0}'\'' | sort |uniq -c -w15 |sort -n'

You should be able to fix this by escaping the date call and the $1 variables:

$ alias downloads=""grep \`date '+%d/%b/%Y'\` access.logs | egrep 2765330645ae47d292c9ceac725d744e.py |awk '{print \$1, \$4, \$5, \$7, \$8, \$9, \$10}' | sort |uniq -c -w15 |sort -n""
$ alias downloads
alias downloads='grep `date '\''+%d/%b/%Y'\''` access.logs | egrep 2765330645ae47d292c9ceac725d744e.py |awk '\''{print $1, $4, $5, $7, $8, $9, $10}'\'' | sort |uniq -c -w15 |sort -n'

Check if you're able to run this successfully. Ideally, you'd define the alias in single-quotes, but the presence of single quotes within the alias itself makes that tricky in your situation."