Bash 别名/函数和命令行选项

Bash 别名/函数和命令行选项

我想设置一个别名来启动 nedit 以及命令行选项 -noautosave (由于文本文件最大为 500MB)。看似简单的事情:

alias nn="nedit -noautosave $1 &"

只是引发一些错误“没有权限”不同的文件和另一个错误寻找匹配的“'”时出现意外的 EOF“意外的文件结束”

我在 Google 搜索后发现的一种解决方案是检查引号,但我看不到它们有任何可能的错误。

我还尝试声明一个函数:

function nn () { nedit -noautosave $1 &}

也因同样的错误而失败。

答案1

如果您只想在要打开的文件之一大于给定大小时运行,请尝试以下操作(我使用的是 100M,但您可以设置自己的大小限制)nedit-noautosave

function nn() { 
    big=0;
    let big+=$(find "$@" -size +100M|wc -l)
    if [ $big -gt 0 ]; then
     nedit -noautosave -- "$@" &
    else
     nedit -- "$@" &
    fi
}

man nedit

   --  Treats all subsequent arguments as file names,
       even if they start with a dash.  This is so NEdit
       can access files that begin with the dash
       character.

答案2

您不能将参数传递到alias.您必须使用 a function,所以您走在正确的轨道上。您只是在使用该function命令时出现了拼写错误。然而,其中任何一个都可以:

$ nn () { nedit -noautosave -- "$@" & }

-或者-

$ function nn() { nedit -noautosave -- "$@" & }

如果需要删除它,请使用unset命令,ie unset -f nn

如果您想以这种方式打开一系列文件,我也会使用,"$@"来代替。$1

bash手册页摘录

@      Expands to the positional parameters, starting from one.  When the 
       expansion occurs within double quotes, each parameter expands to a 
       separate word.  That is, "$@" is equivalent  to  "$1" "$2" ...  If 
       the double-quoted expansion occurs within a word, the expansion of 
       the first parameter is joined with the beginning part of the original 
       word, and the expansion of the last parameter is joined with the last
       part of the original word.  When there are no positional parameters,
       "$@" and $@ expand to nothing (i.e., they are removed).

例子

$ function nn() { nedit -noautosave -- "$@" & }

$ nn ~/.bashrc 
[3] 19830

答案3

如果别名的全部目的是将选项应用于-noautosave您编辑的任何文件,那么

alias nn='nedit -noautosave'

应该足够了。然后您可以将其用作

nn your_file &

答案4

alias nn="nedit -noautosave $1 &"

变量扩展在双引号内解释。如果您从.bashrcshell 命令行运行该命令,则没有位置参数(它们将是传递给 shell 的参数),因此$1扩展为空字符串,别名值为nnedit -noautosave &。因此,当你运行时nn /path/to/file.txt,它被扩展为nnedit -noautosave & /path/to/file.txt。错误消息“权限被拒绝”是因为/path/to/file.txt不可执行。

您可以使用别名alias nn='nedit -noautosave $1 &'来防止扩展并保留内部。$1然而,这并不会更好,因为别名不带参数,它们会被就地替换。 So$1将在扩展别名时被第一个位置参数替换,这并不比以前好。

function nn () { nedit -noautosave $1 &}

这基本上是正确的。如果您遇到与以前相同的错误,那是因为别名nn仍然被定义,并且别名优先于同名的函数。用于unalias nn取消定义别名。

该函数应该这样写:

function nn () { nedit -autosave "$@" & }

如果文件名中存在空格或通配符,则需要使用双引号。使用"$@"代替可以"$1"让你传递多个参数。

相关内容