Unexpected Error "file name too long" and bad output of `head -1` ending in ^M

89 Views Asked by At

I’m currently working on a zsh script on my Mac to automate a process. The script involves reading the first line of a .txt file from a distant directory and passing it to another function.

Here’s the function I’ve written:

function f1() {
  # Read the first line of the file
  local line1="$(head -n 1 "$1" | tr -d '\n' | tr -d '^M')"

  # Compute the values using a different function
  local value1=$(f2 "$line1")

  echo "$value1"
}

However, when I call this function with a directory path that is a very long string (e.g., Folder1/folder2/folder3/...), I encounter an error and the output is incorrect.

When I test line1=$(head -n 1 "$dir" | tr -d '\n' | tr -d '^M'), I get the following error:

$line1

zsh: file name too long: First line of file.^M

Here, First line of file. is the first line of the file that I want to read. I’ve tried removing trailing new lines with tr -d '^M' and tr -d '\n', but neither approach seems to help. Also, the error is not there when the directory name is short, and the functions are evaluated correctly.

I’m at a loss as to why this is happening. It seems like a very peculiar bug, and I haven’t been able to find much information on it. Any insights or suggestions on how to fix this issue would be greatly appreciated.

0

There are 0 best solutions below