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

  • If you just need to confirm that a directory exists, you can use the path exists builtin. If you need to make sure that it is a directory (rather than a file), see the custom command path is-directory below:

    path exists

    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.

    path is-directory

    The following custom command should both confirm that the path exists and that it is a directory:

    def "path is-directory" [] {
      let type = ( describe -d | get type)
      let input = $in
      match $type {
        string => {
          try {
            let filetype = ls -D $input | get type.0
            $filetype == dir
          } 
          | default false
        }
    
        list => {
          $input | each { path is-directory }
        }
    
        _ => { error make { msg: "Only accepts string or list" }}
      }
    }
    

    The same examples above can then be used with this command. For instance:

    [ '.', '/usr/bin/ls', '/home', 'MRE'] | path is-directory
    # => ╭───┬───────╮
    # => │ 0 │ true  │
    # => │ 1 │ false │
    # => │ 2 │ true  │
    # => │ 3 │ false │
    # => ╰───┴───────╯