0

I'm really new to Unix and currently I need to make an alias that checks a file whether it is regular and readable. If its irregular, then I need to return 1 as the exit code and not test if its readable. If its unreadable, I need to return 2 as the exit code.

alias test="if [ ! -f filename ] ; then echo 'Irregular file'; exit 1 ; fi; if [ ! -r filename ]; then echo 'Unreadable file'; exit 2; fi;

The problem is now when I run it, the exit will close my entire client. Any way to get around this?

  • You could write an alias that wraps a shell command (alias mytest="sh -c ' ... '") that performs the tests and exits with the specified status – steeldriver Oct 2 '16 at 23:44
1

A shell function should be able to return a value you like:

checktype() {
    if [ ! -f "$1" ] ; then 
        echo 'Irregular file'
        return 1
    fi 
    if [ ! -r "$1" ]; then 
        echo 'Unreadable file'
        return 2 
    fi
    return 0
}
$ checktype /dev/stdin ; echo $?
Irregular file
1

Also, test is an awful name for an alias or a function, since it's a standard (builtin) utility.


I realize that alias is an awful choice, but currently it's being required by a professor.

Okay, this changes things a bit. My suggestion would be to show the prof a more suitable solution, and explain why the simple one doesn't work.

But in case that won't work, and you really must use an alias, consider that the return value is actually just the return value of the last command that was executed. You should be able to rig up something that returns a value you want...

(If it's homework, I don't think it would be fair to give a full solution immediately. Spoilers below.)

Hint: You already used a command that returns an arbitrary value.

0

alias is a bad choice here. Put those lines into a bash script file.

#!/bin/bash
if [ ! -f filename ];
 then echo 'Irregular file'; exit 1 ;
fi;
if [ ! -r filename ];
 then echo 'Unreadable file'; exit 2;
fi;

It will work as intended.

  • I realize that alias is an awful choice, but currently it's being required by a professor. I really appreciate your time and response though. – Tommy Oct 2 '16 at 20:06
  • Wait. You can not return values from alias. It is not a function, it is text substitution only. May be you can write values to a temp file to be read later. But you can not return value because you can not call alias. – Barafu Albino Oct 2 '16 at 20:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.