shellfile-ionushell

How do I check if a directory exists in a Nushell script?


I would like to know how I check if a directory exists in Nushell?


Solution

  • Use the path exists builtin. Examples:

    > "/home" | path exists
    true
    
    > "MRE" | path exists
    false
    
    > "./nu-0.71.0-x86_64-unknown-linux-gnu" | path exists
    true
    
    > [ '.', '/home', 'MRE'] | path exists
    ╭───┬───────╮
    │ 0 │ true  │
    │ 1 │ true  │
    │ 2 │ false │
    ╰───┴───────╯
    > [ '.', '/home', 'MRE'] | all {path exists}
    false
    > [ '.', '/home', 'MRE'] | any {path exists}
    true
    
    > if ([ '.', '/home', '/proc'] | all {path exists}) {
        "All directories exists"
    } else {
        "One or more directories are missing"
    }
    All directories exists
    

    (^Thanks to @Raze for the simplification using all.)

    See help path exists for more details and help path for more path helper builtins.