0

I need concise and readable function to be used in bash script which will take as input:

  • absolute path (e.g. /home/user/tmp/data/sample1.txt )
  • new filename name (e.g. extended_sample.dat )

and return

absolute path with new filename (e.g. /home/user/tmp/data/extended_sample.dat )

Thank you in advance!

1

Note, the return statement in bash functions is used to return a numeric value as a status code.

How it may look in most simple case:

#!/bin/bash

path="/home/user/tmp/data/sample1.txt"
new_name="extended_sample.dat"

function get_new_path() { echo "${1%/*}/$2"; }

new_path=$(get_new_path "$path" "$new_name")
echo "$new_path"

The above will output:

/home/user/tmp/data/extended_sample.dat
  • 2
    Can't you just do "$(dirname "$1")/$2" ? – xenoid Feb 18 '18 at 12:41
4

There's 2+1(bonus) commands that make life easy with dealing with path names:

  • basename - strip directory and suffix from filenames
  • dirname - strip last component from file name

  • readlink - print resolved symbolic links or canonical file names

So to answer your question:

old_path=/home/user/tmp/data/sample1.txt
new_file=extended_sample.dat

new_path="$(dirname $old_path)/$new_file"

Or to change the path name of the original file:

alt_path=/mnt/newroot/foo

new_path="$alt_path/$(basename $old_path)"

Extract full location of the running script (works if the script is executed off its own file):

dirname $(readlink -f ${0})

With these 3 commands you can do most of your path manipulations easily.

0

Just playing around with bash namerefs:

path_replace_file () {
    local -n pathvar="$1"
    pathvar="${pathvar%/*}/$2"
}

pathname="/home/user/tmp/data/sample1.txt"

printf 'pathname before = %s\n' "$pathname"
path_replace_file pathname extended_sample.dat
printf 'pathname after  = %s\n' "$pathname"

Output:

pathname before = /home/user/tmp/data/sample1.txt
pathname after  = /home/user/tmp/data/extended_sample.dat

The path_replace_file function takes a variable name as its first argument. In the function pathvar acts like an alias (a name reference) for that variable.

The function replaces the filename portion of the value of $pathval with whatever is given as the second argument to the function.

This requires bash 4.3 or later.

Changing local -n to typeset -n will make it work in ksh93 too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.