简体   繁体   中英

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?

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
}

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM