Ray Andrews
Ray Andrews

Reputation: 542

bash: capture '\*' in a command line

function abc ()
{
   echo "You typed exactly this: $1"
}

Now run it:

myprompt$ abc abc\*

And I get:

You typed exactly this: abc*

I'm writing a function in which I need to capture the entire argument, including the backslash, for future use. Can it be done? I've tried every combination of quotes and 'set's and nothing keeps the backslash there. I know I can escape it, but then the argument as typed would not be identical to the argument as echoed. Note that you get the argument back perfectly via 'history'. How can I capture it inside my function, backslash and asterisk and all?

Upvotes: 2

Views: 173

Answers (4)

Ray Andrews
Ray Andrews

Reputation: 542

All,

It looks like it is possible to capture an exact command line within a function. As I suspected, 'history' gives us a way:

function exact_line ()
{
str1=`history 1`
str2=($str1)
str3=
# This isn't very elegant, all I want to do is remove the 
# line count from the 'history' output. Tho this way I do
# have surplus spaces removed as well:
for ((i=1; ; i++))
do
    str3="$str3 ${str2[$i]}"
    if [ -z ${str2[$i]} ]; then break; fi
done
echo -e "Your exact command line was:\n\n$str3"
}

Thoughts? Can this be improved?

Upvotes: 1

Will Bickford
Will Bickford

Reputation: 5386

You could always take the shotgun vs fly approach and implement your own shell. :)

Or tone it down a bit and find a shell that supports the input mechanism you want.

Note that you would have to change your login settings to utilize a "verbatim-shell".

Upvotes: 1

Kevin
Kevin

Reputation: 56059

You can't get the arguments exactly as typed. Bash evaluates them before your function ever sees them. You'll have to escape or quote it.

abc abc\\*
abc 'abc\*'

Upvotes: 2

srgerg
srgerg

Reputation: 19329

The shell interprets the \ character on the command line as an escape character that removes any special meaning from the following character. In order to have a literal \ in your command line, you need to persuade the shell to ignore the special meaning of \ which you do by putting a \ before it. Like this:

myprompt$ abc abc\\\*

Notice there are three \ characters. The first tells the shell to ignore the special meaning of the following character - which is the second \. The third \ tells the shell to ignore the special meaning of the *.

Another way to persuade the shell not to interpret the \ as an escape character is to put your argument in single quotes. Like this:

myprompt$ abc 'abc\*'

Upvotes: 3

Related Questions