I just wanted to ask whether there is any command which would work on common shells (bash, dash, kornshell)? It is supposed to check if the line variable contains any part of the path.
if [[ $line =~ "$PWD"$ ]] ;then
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
In any POSIX-compatible shell you can do:
case $line in (*"$PWD"*) # whatever your then block had ;;esac
This works in bash, dash, and just about any other shell you can name.
It can also be used to handle multiple possibilities easily. For example:
case $line in
(*"$PWD"*)
echo $PWD match!
;;
(*"$OLDPWD"*)
echo $OLDPWD match!
;;
(*)
! echo no match!
;;esac
You can also use alternation:
case $line in (*"$PWD"*|*"$OLDPWD"*)
echo '$OLDPWD|$PWD match!'
;;esac
Note the use of quoting above:
case $line ...- The object of a
casestatement will not be split on either$IFSor be used as a pattern for filename gen. This is similar to the way the left argument in a[[test is treated.
- The object of a
(*"$PWD"*)- Here also a shell expansion is not subjected to either
$IFSor filename generation – an unquoted expansion will neither split nor glob. - But an unquoted expansion here might be construed as a pattern rather than a literal string though, and so an expansion might mean more than one thing depending on whether or not it is quoted.
- It is important to quote any variable used in a pattern that should be literally interpreted, in the same way you would quote pattern chars which you wanted interpreted literally.
- For example, if
$PWDcontained a*and was not quoted it would be construed as a pattern object and not as a literal*to be searched for.
- Here also a shell expansion is not subjected to either
Method 2
Yes, recent versions of bash can do this:
$ pwd /home/terdon $ line="I'm in /home/terdon" $ [[ "$line" =~ "$PWD"$ ]] && echo yes yes
The same syntax works in zsh and ksh but not in dash. As far as I know, dash has no such capabilities.
Note that your regex is checking whether the variable $line ends with $PWD. To check if $PWD matches anywhere in $line, remove the $:
$ line="I'm in /home/terdon, are you?" $ [[ "$line" =~ "$PWD" ]] && echo yes yes
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0