Wednesday, May 8, 2024
 Popular · Latest · Hot · Upcoming
8
rated 0 times [  8] [ 0]  / answers: 1 / hits: 943  / 1 Year ago, sat, march 18, 2023, 3:14:09

I have the following bash command:



$(ls -l /var/ | grep www) > cat folder_exists


but it is not working properly. What I hope to achieve is a command, that checks to see if there is a www folder located inside the /var/ folder, and prints the result of that particular command to the file folder_exists. I have also tried to retype the command numerous times, example given



cat $(ls -l /var/ | grep www) > folder_exists


or even



cat $(ls -l /var | grep www) > folder_exists


just in case that slash did the damage, but to no avail.



My problem is that even though I am creating the file folder_exists, I fail to print the output to it. Could somebody please show me where I have gone wrong?


More From » bash

 Answers
1

Better do that:



if [ -d /var/www ] ; then touch folder_exists ; else touch folder_absent ; fi


The first version of the command does the following: $( ... ) is first replaced by whatever was produced by .... Since you call ls -l | grep www, you are either getting a line with multiple words, or nothing. In the first case it is attempted to be executed, but that makes little sense. What will you get if you type



drwxr-xr-x 15 root root     4096 Aug 20 13:48 log


at the command prompt? There is no command called drwxr-xr-x. If you use the cat $( ls -l /var | grep www) form, then first the $( ... ) is replaced by what was produced by ..., then cat interpretes it as a list of files to cat (starting with drwxr-xr-x; most likely, there is no such file).



Moreover, if you attempt to do something like that:



command > cat file


What will happen is that cat is interpreted as a filename to store the output of command, and not as a command. To interpret cat as a command, you need a pipe sign, like you correctly used in ls | grep:



command | cat


However, if your purpose is to store the output of command in a file, then just use



command > file


As a matter of fact, you could do



ls /var | grep www > file


This file will be empty only if there is no www folder in ls. But beware! if there is a folder /var/ewwwocks, then the file will also contain a line. Better to use simply



ls /var/www > file


Long story short, use the conditional construct if ... ; then ... ; else ... ; fi


[#36048] Sunday, March 19, 2023, 1 Year  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ciousuntru

Total Points: 352
Total Questions: 124
Total Answers: 95

Location: Grenada
Member since Tue, Oct 12, 2021
3 Years ago
ciousuntru questions
;