简体   繁体   English

shell 别名在主目录中执行

[英]shell alias executes in home directory

I have following line in my .zshrc file:我的.zshrc文件中有以下行:

alias clean="sed -i 's/\r//g; s/    /\t/g' $(find . -maxdepth 1 -type f)"

but when I try to execute it in /path/to/some/directory the output is:但是当我尝试在/path/to/some/directory中执行它时,output 是:

sed ./.Xauthority
./.lesshst: No such file or directory

.Xauthority and .lesshst are both in my home directory. .Xauthority.lesshst都在我的主目录中。

Substitutiong .替换. with $(pwd) dos not help.使用$(pwd)没有帮助。

When defining the alias you've used double quotes to encompass the entire (alias) definition.在定义别名时,您使用了双引号来包含整个(别名)定义。 This has the effect of actually running the find command at the time the alias is defined.这具有在定义别名时实际运行find命令的效果。

So when the alias is created it will pick up a list of files from the directory in which the alias is being defined (eg, in your home directory when sourcing .zshrc ).因此,当创建别名时,它将从定义别名的目录中获取文件列表(例如,在获取.zshrc时在您的主目录中)。

You can see this happening in the following example:您可以在以下示例中看到这种情况:

$ cd /tmp

$ pwd
/tmp

$ ls -l
total 36036
drwxrwxrwt+ 1 myid None                  0 Oct 10 11:31 ./
drwxr-xr-x+ 1 myid None                  0 Jul 12 17:28 ../
-rw-r--r--  1 myid Administrators        0 Oct 10 11:31 a
-rw-r--r--  1 myid Administrators        0 Oct 10 11:31 b
-rw-r--r--  1 myid Administrators        0 Oct 10 11:31 c
-rw-r--r--  1 myid Administrators        0 Oct 10 11:31 d
-rw-r--r--  1 myid Administrators 36864002 Jun  6 17:29 giga.txt
drwx------+ 1 myid Administrators        0 Mar  8  2020 runtime-xward/

$ alias clean="sed -i 's/\r//g; s/    /\t/g' $(find . -maxdepth 1 -type f)"
$ alias clean
alias clean='sed -i '\''s/\r//g; s/    /\t/g'\'' ./a
./b
./c
./d
./giga.txt'

Notice how the find was evaluated at alias definition time and pulled in all of the files in my /tmp directory.请注意如何在别名定义时评估find并提取我的/tmp目录中的所有文件。

To address this issue you want to make sure the find is not evaluated at the time the alias is created.要解决此问题,您需要确保在创建别名时评估find

There are a few ways to do this, one idea being to wrap the find portion of the definition in single quotes, another idea would be keep the current double quotes and just escape the $ , eg:有几种方法可以做到这一点,一个想法是将定义的find部分用单引号引起来,另一个想法是保留当前的双引号并转义$ ,例如:

$ alias clean="sed -i 's/\r//g; s/    /\t/g' "'$(find . -maxdepth 1 -type f)'
$ alias clean
alias clean='sed -i '\''s/\r//g; s/    /\t/g'\'' $(find . -maxdepth 1 -type f)'

$ alias alias clean="sed -i 's/\r//g; s/    /\t/g' \$(find . -maxdepth 1 -type f)"
$ alias clean
alias clean='sed -i '\''s/\r//g; s/    /\t/g'\'' $(find . -maxdepth 1 -type f)'

Notice in both cases the alias contains the actual find command instead of the results of evaluating it in the current directory.请注意,在这两种情况下,别名都包含实际的find命令,而不是在当前目录中对其进行评估的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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