I assign command
ls to my variable
my_File but when I run it as
$my_File it does not work. Can you please explain why?
#!/bin/bash my_File='ls -f | grep -v '\/'' $my_File
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.Sign up to join this community
The line you wrote defines a variable whose value is the string
ls -f | grep -v /. When you use it unquoted, it expands to a list of words (the string is split at whitespace):
| character isn't special since the shell is splitting the string, not parsing it, so it becomes the second argument to the
You can't stuff a command into a string like this. To define a short name for a command, use an alias (if the command is complete) or a function (if the command has parameters and is anything more than passing some default arguments to a single command). In your case, an alias will do.
alias my_File='ls -f | grep -v /' my_File
$ my_File='ls -f | grep -v '\/'' $ $my_File ls: cannot access |: No such file or directory ls: cannot access grep: No such file or directory [snip]
$my_File, bash treats the characters in it as just characters. Thus, for one, the command line has a literal
| character in it, not a pipe.
If you are trying to execute
$my_File on the command line and have the pipes work, you need