Reputation: 4137
I'm learning Linux scripting and trying to set up a function that finds all files in the current directory. I know I could use ls but I'm wondering if there is a way to get the current directory as a command and pass it to an argument.
#!/bin/bash
check_file() {
for f in $1:
do
echo $f
done
}
check_file pwd
This just prints out pwd:, which obviously isn't it.
Upvotes: 7
Views: 12057
Reputation: 3561
$PDW
the present working directory is stored in the variable named $PWD
check_file()
{
for f in "$(ls $PWD)"
do
echo "$f"
done
}
check_file
Display the full working directory name
echo "$PWD"
Display the working directory name
basename "$PWD"
Can also use the symbol *
is a short cut to a list of files in the present working directory .
echo *
Loop through them :
for item in *
do
echo "$item"
done
Function looping through
check_file()
{
for f in *
do
echo "$f"
done
}
check_file
Store the present directory name in a variable and use it in a function
Var=$(basename "$PWD")
func()
{
echo $1
}
func $Var
Upvotes: 1
Reputation: 1
A more modern variant is to use the $(
...)
notation (which can be nested when needed, and is expanded to the output of the command in between $(
and matching )
) instead of the backquotes, eg
check_file $(pwd)
(but $PWD
would work too since shells maintain their PWD
variable, see Posix shell).
Read also the advanced bash scripting guide (which can be criticized but is a good start).
Upvotes: 4
Reputation: 11058
To execute a command and use its output in your script as a parameter, just use back quotes. In your case, it would be:
check_file `pwd`
Upvotes: 6
Reputation: 14715
PWD
variable does exactly what you want.
So just replace pwd
with $PWD
and you are done
Upvotes: 15