SenorDestruction Posted April 7, 2007 Posted April 7, 2007 hi there, having a bit of trouble with something in a shell script, i wonder if you could help me, im using the bourne shell... i have a script which works on a file, but i want to make sure the user hasnt entered a pathname using an if statement, i assume theres a way to use regex here, but i cant seem to get it to work... if [ $file = ***Not sure what to enter*** ] then echo "$file: can't be a pathname" when using awk i know you have to use a tilde rather than an = when using regular expressions and if statements, but that doesnt work here... thanks for your help, and if anyone has any questions of a similar nature, here would probably be a reasonable place to ask them... Quote
SomeoneE1se Posted April 7, 2007 Posted April 7, 2007 use a regex to make sure the last char is not a / and that should solve your problem you may also want to make sure the file exists depending on what you're trying to do http://www.ilovejackdaniels.com/regular_ex...cheat_sheet.png Quote
SenorDestruction Posted April 7, 2007 Author Posted April 7, 2007 yeah i assumed a regular expression was needed, but im not sure of the syntax to use it within the if statement code i showed. Quote
kdb Posted May 9, 2007 Posted May 9, 2007 You could do something like this. . . if [[ $file == */]]; then echo whatever fi Then again, this will only check for a string ending with a '/'. What if the user enters '/etc' or '/usr/bin' for example? I'm sure you can figure out how to modify the example to check for these as well. BTW, you should check out the Advanced Bash-Scripting Guide hxxp: tldp. org/LDP/abs/html/ it also has a section on Regular Expressions. kdb Quote
wetelectric Posted May 9, 2007 Posted May 9, 2007 If the path name is to a file or folder one just has to check whether it exists. So using the -x or -e, i forget, should do it. Quote
cooper Posted May 9, 2007 Posted May 9, 2007 -e = exists -x = exists and is accessible -d = exists and is a directory -f = exists and is a file Remember that '[' is actually a program (part of coreutils on Linux) so you need to have a space between it and whatever comes next. Good: if [ -x "file.txt" ] ; then echo YES; fi Bad: if [-x "file.txt" ] ; then echo YES; fi Quote
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.