Escaping a string with quotes in bash alias file
I'd like to put the following command in my ~/.bash_aliases
file:
grep screen /var/log/auth.log|grep "$(date|awk '{print $2" "$3}')"
I've tried putting the following in the alias file:
alias unlocks=grep screen /var/log/auth.log|grep "$(date|awk '{print $2" "$3}')"
but I get the following:
bash: alias: screen: not found
bash: alias: /var/log/auth.log: not found
Presumably, this is because of the spaces in the command string, which would normally be solved by quoting the entire string, but I'm already using two types of quotes and I can't work out how to escape them correctly.
Please can someone help?
alias foo="my command with"quotes""
should work most of the time
EDIT: As bash
will evaluate the string, you also need to escape other special characters like $
In your case: alias unlock="grep screen /var/log/auth.log|grep "$(date|awk '{print $2" "$3}')""
should do the trick.
Don't try to make something this complex an alias. Define a function in .bashrc
instead.
unlocks () {
grep screen /var/log/auth.log | grep "$(date +"%b %d")"
}
Also, don't use awk
when you can just adjust the output of date
directly. However, you can use awk
to replace both instances of grep
:
unlocks () {
awk -v date=$(date +"%b %d") '/screen/ && $0 ~ date' /var/log/auth.log
}
There is a simple way and a hard way.
The simple way: Put the code into a script file called unlocks
inside the folder $HOME/bin
. In most systems, that folder gets added to the path. Use chmod +x $HOME/bin/unlocks
to make the script executable.
The hard way: You can use nested quotes but it's ugly, brittle and ... I don't recommend it. But if you must, it would look like this:
alias unlocks='grep screen /var/log/auth.log|grep "$(date|awk '"'"'{print $2" "$3}'"'"')"'
To get a single nested single quote in a single quoted string, you need '"'"'
The first tick ends the current string. The "'"
gives you a single quote which the shell will append the current string. The last tick then continues the string.
alias unlocks="..."
won't work in this case because it will immediately run date|awk '{print $2" "$3}'
and put the result into the alias.
上一篇: 在while循环中检查BASH字符串是否有单引号?
下一篇: 在bash别名文件中使用引号转义字符串