I have defined a test alias as:

alias testalias='python3 -c "f = open(\"/tmp/testopenfile\", \"w+\"); f.write(\"hi\n\")"'

It works fine when I run it directly through terminal. I can cat /tmp/testopenfile normally. I have also defined a helper function to background and mute error and output of programs. I thought of using this function with some aliases that takes long time or that are on while loop (not this one as its just example). It is defined like this:

detach is a function
detach ()
    $1 > /dev/null 2> /dev/null &

I am using bash, and I tried to combine those two things. When I tried detach testalias, it doesn't seem to work (/tmp/testopenfile doesn't seem to be created). It looks like testalias is directly is passed and not evaluated. What is the hack for making this evaluate before passing.

Also, this code creates the file:

python3 -c "f = open(\"/tmp/testopenfile\", \"w+\"); f.write(\"hi\n\")" 1>/dev/null 2>/dev/null &

1 Answer 1


Replace the alias with a function.

testalias() {
    python3 -c 'f = open("/tmp/testopenfile", "w+"); f.write("hi\n")'
detach ()
    "$@" > /dev/null 2> /dev/null &

Bash only looks at the first word of a command for alias expansion, so the function gets the literal argument testalias. (I think zsh has "global" aliases which would be expanded anywhere on the command line, but I doubt you'd want e.g. echo testalias to expand the alias contents.)

Alias expansion also happens early in the parsing process, way before $1 is expanded, so when the function runs, $1 expands to just the same testalias, and stays like that. It would probably give you an error about not finding the command testalias, except that stderr was redirected to /dev/null, so you don't see the error.

In fact, an alias in a function is expanded when the function is parsed, not when it's used.

$ alias foo="echo abc"
$ f() { foo; }
$ alias foo="echo def"
$ g() { foo; }
$ f
$ g

With testalias a function, it's found when the testalias command is looked up.


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.