简体   繁体   English

目录路径中的Bash变量空间

[英]Bash variable space in directory path

How can I remove a white space when I use a variable in a directory path. 在目录路径中使用变量时如何删除空格。 For example, I'm trying to do 例如,我正在尝试

alias test='echo /david/$1'

and when I try 当我尝试

test hhh

this produces 这产生

/david/ hhh

with a white space before the variable. 在变数前加上空白。 It seems very simple but I can't find a solution. 看起来很简单,但是我找不到解决方案。

alias doesn't do parameter expansion. alias不进行参数扩展。 At all. 完全没有 Use a function instead. 改用一个函数。

test (){
  echo "/david/$1"
}

man :

There is no mechanism for using arguments in the replacement text. 在替换文本中没有使用参数的机制。 If arguments are needed, a shell function should be used (see FUNCTIONS below). 如果需要参数,则应使用shell函数(请参见下面的函数)。 [...] For almost every purpose, aliases are superseded by shell functions. [...]对于几乎所有目的,别名都被shell函数取代。

As a part of alias expansion a space is added at the end of the expanded string (otherwise no argument could be added, like alias ll='ls -l' . So ll -a would be expanded to ls -la which would be wrong). 作为别名扩展的一部分,在扩展字符串的末尾添加了一个空格(否则不能添加任何参数,例如alias ll='ls -l' 。因此ll -a将扩展为ls -la ,这是错误的)。 So I see no solution to this problem anything else then to use function as Ignacio proposed. 因此,除了Ignacio提出的功能之外,我看不到其他解决方案。

Anyway using test as function or alias is not the best thing to do as it is a built-in command (if no aliased or named a function). 无论如何,将test用作函数或别名并不是最好的做法,因为它是内置命令(如果没有别名或命名为函数)。 You can check how a mnemonic will be interpreted using the type bash built-in. 您可以使用内置的bash type检查如何解释助记符。

I defined an alias and a function called test : 我定义了一个别名和一个称为test的函数:

$ type test
type test
test is aliased to `echo /xxx/'

$ type -a test
type -a test
test is aliased to `echo /xxx/'
test is a function
test () 
{ 
    echo "/yyy/$1"
}
test is a shell builtin
test is /usr/bin/test

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

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