Unix & Linux Asked by brocharvey on October 31, 2021
I created new directory called dir1
Then I use touch command to add apple banana carrot date egg fish grape ham
After that I created file Wildcards.sh
(incidentally I used nano to create the file).
#!/bin/bash
# This script will include wildcards
find . dir1
echo The contents of dir1 are:$find
echo
Then I executed it to test if it works. It did, but I don’t want it like this.
I ran it like ./Wildcards.sh
And got
.
./ham
./egg
./grape
./date
./Wildcards.sh
./apple
./fish
./carrot
./banana
find: 'dir1': No such file or directory
The contents of dir1 are:
Should should output like this:
The contents of dir1 are: apple banana carrot date egg fish grape ham
Please help me find my mistake?
Unless you have other unmentioned requirements, the line you need is
echo The contents of dir1 are:$(ls dir1)
You can use it either in bash script or directly from command line. If you want to have the file names in a variable e.g. for future use then
files=$(ls Wallpapers)
echo The contents of dir1 are:$files
Answered by Putnik on October 31, 2021
Your script with corrections.
#!/bin/bash
# This script has no wildcards
find_output="$(find dir1)"
echo 'The contents of dir1 are:'"$find_output"
echo
I thought I would add another answer, as all the existing ones have errors.
Some of your errors are:
find
does not need a .
as its first argument. Yes it often does, but…Shell variables should be lowercase. There is a standard for this. And you will get unexpected errors from time to time, if you make them capitals.
Answered by ctrl-alt-delor on October 31, 2021
Here, Try
result=$(find ~/dir1)
echo "The contents of dir1 are: $result"
or
echo "The contents of dir1 are: $(find ~/dir1)"
(Forgive me if what I say is incorrect, I'm not the best with Bash)
result=$(find ~/dir1)
runs find ~/dir1
and then stores it in result
,
$(command)
runs the command inside the ()
s and uses the STDOUT(Standard output/The output of the command) of the command as a temporary variable,
You could also use ${result}
instead which allows for scenarios like echo "${result}asdf"
.
Hope this helps! Forgive me for any improper formatting, This is my first post :P
Answered by Superpowers04 on October 31, 2021
You can't find dir1 when dir1 is your working directory. You never put anything in the variable "$find"
FIND=$(cd ~/dir1; echo *)
echo "The contents of dir1 are: $FIND"
What happens there, is that you change the working directory to dir1 in your home folder, and then let bash show you all contents that are not hidden ("*"). The results are saved in the variable FIND (but if there were errors, they'd be in FIND too). If you want the hidden files and directories too, it would be:
FIND=$(cd ~/dir1; echo .* *)
Answered by Gerard H. Pille on October 31, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP