Home > Mobile >  Find Directory Name and Save as Variable
Find Directory Name and Save as Variable

Time:09-13

I'm trying to find a directory name and save it as a variable. In this case, this directory will always start with the character "2" and be the only such directory in its parent that starts with a "2". I'm trying to do the following but missing something:

#!/bin/bash
existing_dir=find $PARENT_DIR -maxdepth 1 -type d "2*"
rm -r $PARENT_DIR/$existing_dir
mkdir $PARENT_DIR/$((existing_dir 1))
#do stuff in new directory

In particular, I'm trying to grab that number that starts with the "2" (the directory name will always be only numerals), not the full path. Any help would be appreciated!

CodePudding user response:

use basename to fetch only file name but no full path. Then combine it with find when using -exec.

-exec basename {} \;

{} is the placeholder to pass a single file name to -exec called command, and \; is to finish -exec.

You had wrong usage of find. Here shows right style.

find $PARENT_DIR -maxdepth 1 -type d -name '2*' -exec basename {} \;

The whole command is generally equivalent to

for f in `find $PARENT_DIR -maxdepth 1 -type d -name '2*'`;
  do basename ${f};
done

Sum up, you should correct it by using this.

existing_dir=`find . -maxdepth 1 -type d -name '2*' -exec basename {} \;`

CodePudding user response:

Here is how to do it using bash only features:

#!/usr/bin/env bash

parent_dir='/define/some/path/here'

# Capture directories matching the 2* pattern into array
matching_dirs=("$parent_dir/2"*/)

# Regex match captures the numerical leaf directory name
# from the first mach in the matching_dirs array
[[ "${matching_dirs[0]}" =~ ([[:digit:]] )/$ ]] || exit 1
existing_dir="${BASH_REMATCH[1]}"

new_dir="$((existing_dir   1))"

# If could create new directory
if mkdir -p -- "${parent_dir:?}/${new_dir}"; then
  # Deletes old directory recursively
  # @see: https://github.com/koalaman/shellcheck/wiki/SC2115
  rm -r -- "${parent_dir:?}/${existing_dir}"
fi
  • Related