Problems passing a string to if statement
I'm trying to have a script read a text file, line by line, and then back up the directories which will be listed in each line. Obviously, I need to make sure that these are actually directories. So something like this seems to be a simple way to do it:
Code:
#! /usr/bin/bash Code:
if [ -d /some/valid/path/copied/from/the/text/file ]; then echo "IT'S A PATH"; else echo "nope"; fi; |
Can you show me two or three lines from the textfile and say what kind of error the script produce?
|
Sure - this is testfile.txt (I started off thinking I'd use hashes to comment out lines I didn't want, but then realised it was safer to treat any line as junk unless it specifically tested positive as a folder):
Code:
## How to use: |
as in, this is the output:
Code:
This isn't a path: ## How to use: |
Just delete double quotes in test statement:
if [ -d $line ]; then |
I tried that, but as the lines might contain spaces it gives me an error like this on virtually every line it reads -
Code:
readline_test.sh: line 9: [: too many arguments Code:
if [ -d ## How to use: ]; then Code:
if [[ -d $line ]]; then |
use [[ ]] definitely, as per your last comment.
It looks fine to me either way though, can you genuinely prove these paths DO exist? Just use "/etc" for example. |
Are you sure those directories exist? I have just tried your script and it worked fine:
This isn't a path: ## How to use: This isn't a path: This isn't a path: Line 1 - something This isn't a path: Line 2's got a quote mark This isn't a path: Line 3 has "double quotes" This isn't a path: Line 4 has a /slash This isn't a path: Line 5 blah blah blah. This isn't a path: this isn't a comment This isn't a path: ## this is a comment This isn't a path: normal line. This isn't a path: blank line below: This isn't a path: This IS a path! - /tmp/test If you are just testing that format makes sence as path, you can't use -d as it tests existence of directory |
hmm, I must be going mad!
I've tried putting different paths in the text file: Code:
[/tmp/temp] # cat testfile.txt Code:
This is not a path: ## How to use: Code:
[/tmp/temp] # cd /etc |
ok, is the file in unix format? Could there be a little ^M hiding at the end or something?
|
You're a genius. It wasn't, I've changed it to Unix format and it now works. Thank you! :)
|
All times are GMT -5. The time now is 01:03 PM. |