3

I want to assign the path and file name to a variable:

/path/to/myfile/file.txt

For example

MYFILE=$(pwd)$(basename)

How can i do it ?

  • If the purpose is to extract the name of the script itself (as in your own answer), then this is almost a duplicate of the question here: https://unix.stackexchange.com/questions/4650/determining-path-to-sourced-shell-script – Kusalananda Feb 09 '18 at 11:11
  • assigning an arbitrary file name and path is a slightly different question than getting your own script name; which is it? – Jeff Schaller Feb 09 '18 at 11:47
  • well in first i just wanted how to contact output of two linux command , which will provide me full path + myfilename variable. :) – Omar BISTAMI Feb 09 '18 at 17:14

2 Answers2

5

To answer the question as it is stated: This is a simple string concatenation.

somedirpath='/some/path'  # for example $PWD or $(pwd)
somefilepath='/the/path/to/file.txt'

newfilepath="$somedirpath"/"$( basename "$somefilepath" )"

You most likely would want to include a / between the two path elements when concatenating the strings, and basename takes an argument which is a path (this was missing in the question).


Reading your other answer, it looks like you are looking for the bash script path and name. This is available in BASH_SOURCE, which is an array. It's only element (unless you are in a function) will be what you want. In the general case, it's the last element in the array that you want to look at.

In bash 4.4, this is ${BASH_SOURCE[-1]}.

Kusalananda
  • 333,661
  • Thanks for the answer, its clear now ! i have the following code : PATH="/mnt/c/Users/omar_bistami/Documents/testvad/afficher.sh" echo $PATH echo $(basename "$PATH") And i get line 6: basename: command not found I tried basename "$PATH"and $( basename "$PATH" ) But still getting the error , tried in 2 differents env. – Omar BISTAMI Feb 09 '18 at 16:51
  • @OmarBISTAMI That is because PATH is a very special variable used by the shell to look up external utilities. Please use almost any other variable name. Normally, one's own scripts should use lower-case variable names so that they don't accidentally clash with system environment variables. – Kusalananda Feb 09 '18 at 17:08
  • yes... was overridden the path..big thanks! – Omar BISTAMI Feb 09 '18 at 17:13
  • @OmarBISTAMI See addition to my answer. – Kusalananda Feb 09 '18 at 19:37
1

I tried this and it worked :

#!/bin/bash
SCRIPT=$(pwd)$(basename $0)
echo $SCRIPT

If there is a better way, please share.