7

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.

4 Answers 4

15

PWD variable does exactly what you want. So just replace pwd with $PWD and you are done

Sign up to request clarification or add additional context in comments.

Comments

6

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` 

Comments

4

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).

Comments

1

$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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.