问题
I am trying to have an alias with if-then-else condition on a command result.
- the alias will get a file pattern
- if there is just one file it will open the file
- if there is more or less then 1 files - it will indicate with a message.
the alias I have tried is:
alias atest 'if \("ls \!:1" > 0 \) "nedit ls \!:1" else "echo cant open the file" '
回答1:
You can't do this with an alias. An alias can only expand into a one-line command, but if
requires multiple lines.
Instead, use a shell script. The script doesn't have to be in the same language you use interactively, so you can use POSIX shell, which is generally considered much better for programming than C shell (see Csh Programming Considered Harmful).
#!/bin/sh
if [ $# -eq 1 ]
then nedit "$1"
else
echo "Can't open the file"
exit 1
fi
Put this in a file named atest
, give it execute permissions, and put it in a directory that's in your $PATH
.
回答2:
There are a couple of ways, most of them are not very elegant, but the following is the best looking and easiest to create that I have discovered:
alias aliasname '`if (condition == check) echo "echo"` >&/dev/null && code_if_true || code_if_false'
You have the ability to nest if statements following this format, and can also use it as a checker for arguments if you change the interior of the if statement to be
if ("\!:1" =~ "check")
The >&/dev/null is to clean up the output of the function, but is not necessary. If you are interested, there is also a way to make for statements within aliases, but that method is a lot less elegant. I haven't used it but it is necessary if you wish to create an alias with a varying number of arguments. Again, that one is ugly, so at that point I'd just write a function.
回答3:
Building on Jonathan Roberts solution. This is part of a bash script on the local server. Checks for user XXXXX if true, sends through ssh the BASH command. Otherwise sends the TCSH command. The command checks to see if a directory exists returns true or false
if [[ ${LOCAL_USER} == "XXXXX" ]]; then
LOCAL_DIR_EXIST_CHECK=$(ssh -v -q -i ~/.ssh/"${LOCAL_SSH_KEY_FILE}" "${LOCAL_USER}@${LOCAL_SERVER}" "if [[ -d ${LOCAL_CLIENT_DIRECTORY} ]];then echo 'TRUE'; else echo 'FALSE'; fi")
else
LOCAL_DIR_EXIST_CHECK=$(ssh -v -q -i ~/.ssh/"${LOCAL_SSH_KEY_FILE}" "${LOCAL_USER}@${LOCAL_SERVER}" '`if ( -d ' ${LOCAL_CLIENT_DIRECTORY} ') echo "echo"` > & /dev/null && echo TRUE || echo FALSE')
fi
来源:https://stackoverflow.com/questions/44899195/tcsh-alias-with-if-then-else-condition