1

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.

2 Answers 2

6

alias doesn't do parameter expansion. At all. Use a function instead.

test (){
  echo "/david/$1"
}
Sign up to request clarification or add additional context in comments.

3 Comments

To be more explicit, when you type test hhh, you are REALLY sending echo /david/$1 hhh, and because $1 is blank, you are sending echo /david/ hhh
Thanks! :) But, if I want to use an alias (in my .bashrc), must I specify that function there? What I was looking for is something like alias ='command /path-with-variable ... . Is there a way to put that function inside the alias specification?
mmm I just used the function instead the alias and the command works.
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). [...] For almost every purpose, aliases are superseded by shell functions.

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 -l-a which would be wrong). So I see no solution to this problem anything else then to use function as Ignacio proposed.

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). You can check how a mnemonic will be interpreted using the type bash built-in.

I defined an alias and a function called 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

1 Comment

Thanks, this clarifies my question even more :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.