How to store pipe ( | ) in a variable?

bash does not completely re-interpret the command line after expanding variables. To force this, put eval in front:

r="directory1/directory2/direcotry3/file.dat | less -I "
eval "cat path1/path2/$r"

Nevertheless, there are more elegant ways to do this (aliases, functions etc.).


You are trying to mix code and data, which is not a good idea. Instead, define a function which takes a file (directory?) name as an argument, and displays it with less.

view () {
    less -I -p "$2" $1
}

view directory1/directory2/directory3 <searchterm>