Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: Nested backticks in alias cause problems

I'm trying to write an alias which will jump to the descendant directory of cwd which contains a specified file (or the first find found occurrence of such a filename):

The following command combination achieves the desired result:

cd `dirname \`find -name 'MyFile.txt' | sed -n 1p\``

However, I can't seem to escape this in the correct way to create a working alias:

alias jump="cd \`dirname \\\`find -name '$1' | sed -n 1p\\\`\`"

Output:

/*
dirname: missing operand
Try `dirname --help' for more information.
bash: cd: find: No such file or directory

My logic is that backticks need escaping in a double quoted string with a single \ and I can't do \\ gets translated to a single backslash within a string, so the second nested backtick requires 1+2=3.

Any suggestions?

like image 889
KomodoDave Avatar asked Jan 19 '12 15:01

KomodoDave


3 Answers

Backticks are the old form of command substitution, and you can't nest them easily. However, the new $() form does nest easily:

cd $(dirname $(find -name 'MyFile.txt' | sed -n 1p))
like image 137
Lee Netherton Avatar answered Oct 01 '22 01:10

Lee Netherton


An alias cannot take an argument like $1. Use a function instead.

Also use $(command) for command substitution instead of backticks, as it is easier to nest.

The function would be:

jump() {
    cd $(dirname $(find -name "$1" | sed -n 1p))
}
like image 29
dogbane Avatar answered Oct 01 '22 02:10

dogbane


Backticks doesn't offer nesting. Try using command substitution which has the syntax $(..)

In your case it will be

cd $(dirname $(find /path/to/search -name 'MyFile.txt' | sed -n 1p)) 
like image 42
jaypal singh Avatar answered Oct 01 '22 01:10

jaypal singh