Search code examples
stringshellfish

Fish Shell: validate if string contains substring


Currently I'm trying to validate if my string which contains a path contains a specific string.

I've already tried the bash comparison:

  1. if [ $path = $needle ]

and

  1. if [ $path =~ $needle ]

I also try the 'contains' keyword. But i'm not sure if I'm suppose to use this with a string..

Unfortunately these attempts all failed. :/

function next_dir
    set foundcwd 0
    set cwd $PWD
    set error 'There is no next directory to navigate to...'

    if [ -z $cwd ]
        echo $error
    else
        echo $cwd
        for d in ../*/
            set needle (string split "/" -- $d)[2]

            if [ $foundcwd = 1 ]
                cd $d
                break
            end

            if [ $cwd =~ $needle ]
                $foundcwd = 1
            end
        end
    end
end

The goal of my function is to navigate to the next (sibling) directory.

/mnt/c/workingdirectory/repoA --> current directory /mnt/c/workingdirectory/repoB --> navigate to repoB


Solution

  • You want string match.

    if string match -q  -- $needle $path